blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4618794cd93e01a484d9fe00a884c20b8d0322f6 | Sharonno/pythoncode | /sort.py | 355 | 4.15625 | 4 | #-*-coding:utf-8-*-
#!/usr/bin/python
def bubbleSort(a):
l = len(a)
for i in range(l-1):
for j in range(i, l):
if a[i] > a[j]:
tmp = a[i]
a[i] = a[j]
a[j] = tmp
return a
def insertSort(a):
pass
if __name__ == '__main__':
a = [3,2,4,5,1]
print bubbleSort(a)
| false |
fea480bb25c28deacf4bb6bf9910e6dac13c68c2 | DenisSkulovic/Developers-Institute-Bootcamp | /Week 5/Day 3/Daily Challenge/Daily_Challenge.py | 850 | 4.15625 | 4 | # Daily Challenge : Information From The User
# Notice : solve this using a lambda function, even if you can think of another way
# Hint: Look at the lesson on Week4Day4
# Take the following inputs 5 times from the user:
# Name (string)
# Age (int)
# Score (int)
# Build a list of tuples using these inputs, each tuple will contain a name, age and score
# Sort the list by the following priority Name > Age > Score
# If the following tuples are given as input to the script:
# Tom,19,80
# John,20,90
# Jony,17,91
# Jony,17,93
# Json,21,85
# Then, the output of the program should be:
# [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
print(sorted([(input("Name: "), input("Age: "), input("Score: ")) for _ in range(5)], key = lambda tup: str(tup[0]) + str(tup[1]) + str(tup[2])))
| true |
efc0071ea654974230f4c1e1d931b6e78651757d | DenisSkulovic/Developers-Institute-Bootcamp | /Week 4/Day 4/Daily Challenge/Daily_Challenge.py | 1,536 | 4.375 | 4 | # Daily Challenge : Solve The Matrix
# Hint: Look at the remote learning “Matrix” videos
# The matrix is a grid of strings (alphanumeric characters and spaces) with a hidden
# message in it.
# To decrypt the matrix, Neo reads each column from top to bottom, starting from the
# leftmost column, select only the alphanumeric characters and connect them, then he
# replaces every group of symbols between two alphanumeric characters by a space.
# Using his technique, try to decode this matrix:
# 7 3
# Tsi
# h%x
# i #
# sM
# $a
# #t%
# ir!
def neo(*args):
import string
import re
# convert columns to rows
num_of_cols = args[0].__len__()
columns = []
for i in range(num_of_cols):
column = ''
for arg in args:
column += arg[i]
columns.append(column)
# concating the columns into one long string
message = ''.join(columns)
message = message.replace(" ", "")
# replacing the non-alphanumeric characters with spaces
cleaned_message = ''
for char in message:
if char not in (string.ascii_lowercase + string.ascii_uppercase + ''.join([chr(i) for i in range(48, 58)])):
cleaned_message += ' '
else:
cleaned_message += char
# there can be multiple spaces in a row, so the words are extracted and concatinated with just one space
return ' '.join(re.findall("\\b\w+\\b", cleaned_message))
print(neo("7 3", "Tsi", "h%x", "i #", "sM ", "$a ", "#t%", "ir!")) | true |
fc20760f5b5655213185876bebe85cfa83aed778 | DenisSkulovic/Developers-Institute-Bootcamp | /Week 5/Day 1/Daily Challenge/Daily_Challenge.py | 2,955 | 4.40625 | 4 | # Daily Challenge : Old MacDonald’s Farm
# Look carefully at this code and output
# File: market.py
# macdonald = Farm("McDonald")
# macdonald.add_animal('cow',5)
# macdonald.add_animal('sheep')
# macdonald.add_animal('sheep')
# macdonald.add_animal('goat', 12)
# print(macdonald.get_info())
# Output
# McDonald's farm
# cow : 5
# sheep : 2
# goat : 12
# E-I-E-I-0!
# Create the code that is needed to recreate the code above. Here are a few questions to help give you some direction:
# 1. Create a Farm class. How do we implement that?
# 2. Does the Farm class need an __init__ method? If so, what parameters should it take?
# 3. How many method does the Farm class need ?
# 4. Do you notice anything interesting about the way we are calling the add_animal method? What parameters should
# this function have? How many…?
# 5. Test that your code works and gives the same results as the example above.
# 6. Bonus: line up the text nicely in columns like in the example using string formatting
# Expand The Farm
# Add a method to the Farm class called get_animal_types. It should return a sorted list of all the animal types
# (names) that the farm has in it. For the example above, the list should be: ['cow', 'goat', 'sheep']
# Add another method to the Farm class called get_short_info. It should return a string like this: “McDonald’s farm
# has cows, goats and sheep.”
# It should call the get_animal_types function.
# How would we make sure each of the animal names printed has a comma after it aside from the one before last
# (has an and after) and the last(has a period after)?.
class Farm:
def __init__(self, farmer_surname):
self.farmer_surname = farmer_surname
self.animals = {}
def add_animal(self, new_animal, quantity=1):
if new_animal not in self.animals.keys():
self.animals[new_animal] = quantity
else:
self.animals[new_animal] += quantity
print(self.animals)
def get_info(self):
for key, value in self.animals.items():
print(key, ": ", value)
print("\nI-E-A-I-A-I-O!")
def get_animal_types(self):
return list(self.animals.keys())
def get_short_info(self):
strng = f"{self.farmer_surname}'s farm has "
types = self.get_animal_types()
for animal in types:
if len(types) == 1:
strng += f"{animal}s."
print(strng)
return None
elif types.index(animal) == len(types)-1:
strng += f"and {animal}s."
elif types.index(animal) == len(types)-2:
strng += f"{animal}s "
else:
strng += f"{animal}s, "
print(strng)
macdonald = Farm("McDonald")
macdonald.add_animal('cow', 5)
macdonald.add_animal('sheep')
macdonald.add_animal('sheep')
macdonald.add_animal('goat', 12)
macdonald.get_info()
macdonald.get_short_info()
| true |
551ca1db801b534c6952c080c90cc6933dcf466e | 316513979/thc | /Clases/Programas/08.py | 667 | 4.15625 | 4 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
print "Hoy es miércoles"
print '''Diego Armando Santillán Arriaga, 316513979,
Taller de Herramientas Computacionales,
este es un programa que dice "hoy es miércoles"
'''
x=10.5; y=1.0/3; z=15.3
#x, y, z=10.5, 1.0/3, 15.3
H = """
El punto en R3 es:
(x, y, z)=(%.2f,%g,%G)
""" % (x, y, z)
print H
G="""
El punto en R3 es:
(x, y, z)=({laX:.2f},{laY:g},{laZ:G}
""".format(laX=x, laY=y, laZ=z)
print G
import math as m
from math import sqrt
from math import sqrt as s
from math import *
x=16
x=input("Cuál es el valor al que le quieres calcular la raiz:")
print "la raiz cuadrada de %.2f es %f" % (x, m.sqrt(x))
print sqrt(16.5)
print s(16.5)
| false |
7339149fbef79e372fde4e8d39cecda10af25bf8 | 316513979/thc | /Clases/Programas/Tarea05/Problema3LS.py | 1,194 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# 316513979, Diego Armando Santillán Arriaga, Taller de Herramientas Computacionales
# El objetivo de este programa es mostrar una tabla de equivalencia en la que se muestren
# algunas temperaturas medidas en grados centígrados y su equivalencia en grados fahrenheit.
import Problema3L
print 'Las entradas de texto se deben de escribir entre comillas'
a=input ('Convertir de grados (centígrados o fahrenheit): ')
b=input ('a grados (centígrados o fahrenheit): ')
if a == 'centígrados' and b == 'fahrenheit':
ti= input ('Introduce la temperatura inicial en grados centígrados: ')
tf= input ('Ahora introduce la temperatura final en grados centígrados: ' )
print ('Las equivalencias de grados centígrados a grados fahrenheit son: ')
print Problema3L.CentigradosFahrenheit (ti, tf)
else:
if a == 'fahrenheit' and b == 'centígrados':
ti= input ('Introduce la temperatura inicial en grados fahrenheit: ')
tf= input ('Ahora introduce la temperatura final en grados fahrenheit: ')
print ('Las equivalencias de grados fahrenheit a grados centígrados son: ')
print Problema3L.FahrenheitCentigrados (ti, tf)
else:
print ('Error')
| false |
0670edbdd4aac75c4f408c4c38077a96d2b26727 | kurapatirajiv/HackerRank | /ReValidateUIDV2.py | 618 | 4.1875 | 4 | import re
for _ in range(int(input())):
s = input()
# [A-Za-z0-9]{10} : 10 letters of the given sequence
# ([A-Z].*){2} : Matches any character with A-Z and accepts the value which are atleast two
# ([0-9].*){3} : Matches any character with 0-9 and accepts the value which are atleast two
# r'(.).*\1 : whatever character end up in the parentheses is matched against every other character in the string after it to make sure it repeats only once
print('Valid' if all(re.search(r, s) for r in [r'[A-Za-z0-9]{10}',r'([A-Z].*){2}',r'([0-9].*){3}']) and not re.search(r'(.).*\1', s) else 'Invalid') | true |
e73794d3a2868b5b92f25aa167e38bcc1991cbe0 | kurapatirajiv/HackerRank | /Most-Common.py | 563 | 4.1875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
# https://www.hackerrank.com/challenges/most-commons
from collections import OrderedDict
myList = OrderedDict()
for item in raw_input():
myList[item] = myList.get(item,0) + 1
i = 0
# Reverse is set to true, because the sort function sorts the list in increasing order
# The list is internally sorted to support the requirements of printing the elements in alphabetical order
for item in sorted(sorted(myList),key=myList.get, reverse=True):
if i < 3: print item, myList[item]; i = i + 1 | true |
b791359532533f5038d904b457525db5805d9680 | kurapatirajiv/HackerRank | /ValidatingCreditCardNum.py | 863 | 4.375 | 4 | # https://www.hackerrank.com/challenges/validating-credit-card-number
import re
for _ in range(int(input())):
s = input()
joinedStr = "".join(s.split("-"))
# ^[4-6]{1}[0-9]{3} : starting with digits 4,5,6 on one char length,followed by digits 0-9 of length 3
# -[0-9]{4} : starting with hyphen followed by digits 0-9 of length 4 OR
# [0-9]{4}){3}$ : digits 0-9 of length 4
# (-[0-9]{4}|[0-9]{4}){3}$ : Above group is repeated 3 times as first 4 digits are covered
# .*(.)\1{3} : Current character if matches with the next character and the set repeats 3 times ex:4444- then it is invalid
# JoinedStr is passed to the .*(.)\1{3} after removing "-" because consecutive checking would be easier
print('Valid' if (re.match(r'^[4-6]{1}[0-9]{3}(-[0-9]{4}|[0-9]{4}){3}$',s) and not re.search(r'.*(.)\1{3}',joinedStr)) else 'Invalid') | true |
b38fd8d07d205ff53158d664f6e495b5d3c9f13c | yo16/tips_python | /配列/配列基礎.py | 1,743 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 配列基礎
# 3種類ある
# リスト
# タプル
# リストとほぼ同じだが、追加できない
# 辞書
# -------------------
# リスト
print('list-----------------')
# -------------------
# 初期化
listA = [10, 20, 30]
# 参照
print(listA[1])
# 20
# 変更
listA[1] = 21
# 要素を追加
listA.append(40)
# リストを追加
listA.extend([50, 60])
print(listA)
# [10, 21, 30, 40, 50, 60]
# ループで1要素ずつ
for elm in listA:
print(elm)
# 要素数
print('len:' + str(len(listA)))
# 存在
if 21 in listA:
print('exists')
if 99999 not in listA:
print('not exists')
# -------------------
# タプル
print('tuple-----------------')
# -------------------
# 初期化
tupleA = (10, 20, 30)
# 参照
print(tupleA[1])
# 20
# 設定
#tupleA[1] = 22
# TypeError: 'tuple' object does not support item assignment
# 要素を追加
#tupleA.append(40)
# AttributeError: 'tuple' object has no attribute 'append'
print(tupleA)
# (10, 20, 30)
# ループで1要素ずつ
for elm in tupleA:
print(elm)
# 要素数
print('len:' + str(len(tupleA)))
# -------------------
# 辞書
print('dic-----------------')
# dicだと、追加するときに楽.appendとか言わなくていいから。
# -------------------
# 初期化 # 改行が許されている模様
dicA = {
'a':10,
'b':20,
'c':30
}
# 参照
print(dicA['b'])
# 20
# 設定
dicA['b'] = 21
# 要素を追加
dicA['d'] = 40
print(dicA)
# {'b': 21, 'd': 40, 'a': 10, 'c': 30} # 順番は保障されない
# ループで1要素ずつ # 順番は保障されない
for elm in dicA:
print(elm)
# b、d、a、c
print(dicA[elm])
# 21、40、10、30
# 要素数
print('len:' + str(len(dicA)))
| false |
be9d9a2e0a069b2a1cfbfd5ab83f3b70f97af59e | Carmon-Lee/python | /algorithm/leetcode/issymetric.py | 745 | 4.125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.doIsSymmetric(root,root)
def doIsSymmetric(self, node1, node2):
if (node1 and not node2) or (node2 and not node1):
return False
if node1 == node2:
return True
return node1.val == node2.val \
and self.doIsSymmetric(node1.left, node2.right) \
and self.doIsSymmetric(node1.right, node2.left)
if __name__ == '__main__':
print(Solution().isSymmetric(TreeNode(3)))
| true |
5ae951fcb634ea3577b4940bcb4e32d11eef8ae0 | NoelArzola/10yearsofPythonWoot | /1 - intro/get_initials_function.py | 651 | 4.40625 | 4 | # This function will return the first initial of a name
def get_initial(name, force_uppercase=True):
if force_uppercase:
initial = name[0:1].upper()
else:
initial = name[0:1]
return initial
# Ask someones name and return the initials
first_name = input('What is your first name? ')
first_name_initial = get_initial(first_name)
middle_name = input('What is your middle name? ')
middle_name_initial = get_initial(middle_name, False)
last_name = input('What is your last name? ')
last_name_initial = get_initial(last_name, False)
print('Your initials are: ' + first_name_initial + middle_name_initial + last_name_initial) | true |
208300e11d9d799f7ae9ad99dc09ac3ce799437d | NoelArzola/10yearsofPythonWoot | /1 - intro/demos.py | 490 | 4.34375 | 4 | # first_name = 'Noel'
# last_name = 'Arzola'
first_name = input('Please enter your first name: ')
last_name = input ('Please enter your last name: ')
#print(first_name + last_name)
#print('Hello ' + first_name.capitalize() + ' ' + last_name.capitalize())
# output = 'Hello, ' + first_name + ' ' + last_name
# output = 'Hello, {} {}'.format(first_name, last_name)
# output = 'Hello, {0} {1}'.format(first_name, last_name)
#p3 only
output = f'Hello, {first_name} {last_name}'
print (output) | false |
1953dac92a3742111c2953f8478c41c48d7a284f | morin-berk/homework | /tests/homework3/test_task1.py | 955 | 4.21875 | 4 | from typing import List
from homework3.task1 import cache
def test_func_with_int_args():
"""Testing whether caching works
for a func with int arguments"""
@cache(times=2)
def func_int(a: int, b: int) -> int:
"""Just a sample of a func"""
return (a ** b) ** 2
some = 100, 200
val_1 = func_int(*some)
val_2 = func_int(*some)
val_3 = func_int(*some)
val_4 = func_int(*some)
assert val_1 is val_2
assert val_1 is not val_3
assert val_3 is val_4
def test_func_with_list_arg():
"""Testing whether caching works
for a func with a list argument"""
@cache(times=2)
def func_list(a: List) -> List:
"""Just a sample of a func"""
return sum(a)
some = [100, 200]
val_1 = func_list(some)
val_2 = func_list(some)
val_3 = func_list(some)
val_4 = func_list(some)
assert val_1 is val_2
assert val_1 is not val_3
assert val_3 is val_4
| false |
edc9ef8a4613e1040e940201888e09116eab10c8 | bestgopher/dsa | /recursion/binary_search.py | 863 | 4.21875 | 4 | def binary_search(data, target, low, high):
"""
Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False
mid = (low + high) / 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search(data, target, low, mid - 1)
else:
return binary_search(data, target, mid + 1, high)
def binary_search_iterative(data, target):
"""Return True if target is found in the given Python list."""
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
high = mid - 1
else:
low = mid + 1
return False
| true |
d42c55e0d1688414c0f2650ec2d767e4c1dcbd97 | Prot0type1/IS-51Lab4 | /IS51Lab4.py | 1,457 | 4.28125 | 4 | """
this program gives the end user three attempts to answer the question
what is the capital of California will be the question with the answer being Sacramento
set max_tries = 3. a loop iterate three times for each attempt,
we verify if the user input matches the answer.
If verification is correct, print "correct!" , the loop will along with a break statement
if the user fails to answer correctly with 3 tries,
then print "You have used up your maximum allowed attempts.", then print "The correct answer is California"
"""
"""
main
question = "What is the capital of California"
answer = "Sacramento"
ask(question, answer)
ask
tries = 0
loop three times
increment tries
ask user input()
verify if user input is equal to answer
if so, print "Correct" then exit loop
if not correct
print to the user "You have used up your maximum allowed attemptsYou have used up maximum allowed attempts
"The correct answer is Sacramento"
main
"""
def main():
question = "What is the capital of California? "
answer = "Sacramento"
ask(question, answer)
def ask(question, answer, max_tries=3):
tries = 0
ans = ""
while tries < max_tries:
tries += 1
ans = input(question)
if ans == answer:
print("Correct!")
break
if ans != answer:
print("You have used up your maximum allowed attempts.")
main() | true |
80a535c1b4bc3df585ecc5d1152b26e5c33d6de8 | JessicaRiley0301/python | /ajax/rock_paper_scissors.py | 1,747 | 4.28125 | 4 | import random
user_wins = 0
computer_wins = 0
winning_score = 3
total_games = 0
while total_games <= 5:
total_games += 1
print(f"Player Score: {user_wins} Computer Score: {computer_wins}")
user_choice = input("rock, paper, scissors ")
rand_num = random.randint(0,2)
if rand_num == 0:
computer_choice = "rock"
elif rand_num == 1:
computer_choice = "paper"
else:
computer_choice = "scissors"
if user_choice == computer_choice:
print("this round is a tie")
else:
if user_choice == "rock":
if computer_choice == "scissors":
print("you win this round")
user_wins += 1
else:
print("you lose this round")
computer_wins += 1
elif user_choice == "paper":
if computer_choice == "rock":
print("you win this round")
user_wins += 1
else:
print("you lose this round")
computer_wins += 1
elif user_choice == "scissors":
if computer_choice == "paper":
print("you win this round")
user_wins += 1
else:
print("you lose this round")
computer_wins += 1
if total_games == 5:
if user_wins == computer_wins:
print("you tied")
break
elif user_wins > computer_wins:
print("you win the game")
break
else:
print("the computer won the game")
break
if user_wins == 3:
print("you win the game")
break
if computer_wins == 3:
print("the computer won the game")
break | true |
9c6dc0ff3508521d220b900c1fb4871fd032e7f7 | wenxinjie/leetcode | /array/python/leetcode48_Rotate_Image.py | 1,033 | 4.3125 | 4 | # You are given an n x n 2D matrix representing an image.
# Rotate the image by 90 degrees (clockwise).
# Note:
# You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
# Example 1:
# Given input matrix =
# [
# [1,2,3],
# [4,5,6],
# [7,8,9]
# ],
# rotate the input matrix in-place such that it becomes:
# [
# [7,4,1],
# [8,5,2],
# [9,6,3]
# ]
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
row = 0
while row < n-row:
for i in range(row,n-row-1):
matrix[row][i],matrix[i][n-1-row],matrix[n-1-row][n-i-1],matrix[n-i-1][row] =
matrix[n-i-1][row],matrix[row][i], matrix[i][n-1-row], matrix[n-1-row][n-i-1]
row += 1
# Time: O(n^2)
# Space: O(1)
# Difficulty: medium | true |
5983a85441462b0239e8b1e0d73c719387b597a4 | brandon-craig/fifteen-minute-algorithms | /python/mergeSortDivideExample.py | 664 | 4.3125 | 4 | def mergeSort(listOfNumbers):
# If the list of numbers has 0 or 1 items we dont need to do anything
# so just return the list back
if len(listOfNumbers) <= 1:
return listOfNumbers
# We find where the middle of the list of numbers is
# by dividing the length of the list by 2
middleIndex = len(listOfNumbers) // 2
# We are dividing the list of numbers into two halves which I
# am calling leftHalf and rightHalf, respectively.
leftHalf = listOfNumbers[:middleIndex]
rightHalf = listOfNumbers[middleIndex:]
# Here we recusively call mergeSort on the left and right halves
# of the original list of numbers
mergeSort(leftHalf)
mergeSort(rightHalf) | true |
777b17b4aa2c6041ba97c3fa69f9a8a18154b4cd | kodewilliams/college | /Python/Intro to CS/combine_sorted_lists.py | 615 | 4.125 | 4 | def CombineTwoSortedLists(list1, list2):
# If either list is empty, return the other one
if len(list1) == 0:
return list2
elif len(list2) == 0:
return list1
else:
# If lists aren't empty, append them to each other
sorted_list = list1 + list2
# Sort lists
for x in range(len(sorted_list)-1, 0, -1):
for y in range(x):
if sorted_list[y] > sorted_list[y+1]:
temp = sorted_list[y]
sorted_list[y] = sorted_list[y+1]
sorted_list[y+1] = temp
return sorted_list
| true |
200fe96d6fc56f6f0ee91a93efcb7aacb9a9bfdc | kodewilliams/college | /Python/Intro to CS/imperial_to_metric.py | 1,172 | 4.3125 | 4 | def GetMilesToKilometers(num_miles):
'''
This function should return the miles converted to kilometers. Replace the
line below with the correct code.
'''
return num_miles * 1.61
def GetPoundsToKilograms(num_pounds):
'''
This function should the miles converted to kilometers. Replace the line
below with the correct code.
'''
return num_pounds * 0.45
def GetFahrenheitToCelsius(temp_fahrenheit):
'''
This function should the fahrenheit temperature converted to celsius.
Replace the line below with the correct code.
'''
return (temp_fahrenheit - 32) * (5/9)
# You don't need to change anything below this line.
num_miles = float(input("Enter distance (in miles): "))
num_pounds = float(input("Enter weight (in pounds): "))
temp_fahrenheit = float(input("Enter temperature (in fahrenheit): "))
num_kilometers = GetMilesToKilometers(num_miles)
num_kilograms = GetPoundsToKilograms(num_pounds)
temp_celsius = GetFahrenheitToCelsius(temp_fahrenheit)
print('That\'s', num_kilometers, 'kilometers,', num_kilograms,
'kilograms, and', temp_celsius,
'celsius. Now you sound like you\'re from London!')
| true |
61ca5d8a8479c991d5171e5f51d357bbe3bd2182 | kodewilliams/college | /Python/Intro to CS/get_location_path.py | 393 | 4.25 | 4 | from locations import location_dict
# Write your code below this line.
place = input('Enter location: ')
if place not in location_dict:
if place in location_dict.values():
print (place)
else:
print ('Location not found.')
else:
print (place, end='')
while (place in location_dict):
place = location_dict[place]
print (',', place, end='')
| true |
d732b391e7d23d7fab100042ecb9a59f3e8e7630 | UtsavRatna/Descent_py | /hackerrank/highestValuePalindrome.py | 2,730 | 4.46875 | 4 | """
Palindromes are strings that read the same from the left or right, for example madam or 0110.
You will be given a string representation of a number and a maximum number of changes you can make. Alter the string, one digit at a time, to create the string representation of the largest number possible given the limit to the number of changes. The length of the string may not be altered, so you must consider 's left of all higher digits in your tests. For example is valid, is not.
Given a string representing the starting number and a maximum number of changes allowed, create the largest palindromic string of digits possible or the string -1 if it's impossible to create a palindrome under the contstraints.
Function Description
Complete the highestValuePalindrome function in the editor below. It should return a string representing the largest value palindrome achievable, or -1.
highestValuePalindrome has the following parameter(s):
s: a string representation of an integer
n: an integer that represents the length of the integer string
k: an integer that represents the maximum number of changes allowed
Input Format
The first line contains two space-separated integers, and , the number of digits in the number and the maximum number of changes allowed.
The second line contains an -digit string of numbers.
Constraints
Each character in the number is an integer where .
Output Format
Print a single line with the largest number that can be made by changing no more than digits. If this is not possible, print -1.
Sample Input 0
4 1
3943
Sample Output 0
3993
Sample Input 1
6 3
092282
Sample Output 1
992299
Sample Input 2
4 1
0011
Sample Output 2
-1
Explanation
Sample 0
There are two ways to make a palindrome by changing no more than digits:
, so we print .
"""
def highestValuePalindrome(s, n, k):
s=list(s)
if n<=k:
return '9'*n
mink=[0]*(n//2+1)
for i in range(n//2-1,-1,-1):
if s[i]!=s[n-1-i]:
mink[i]=mink[i+1]+1
else:
mink[i]=mink[i+1]
if mink[0]>k:
return '-1'
i=0
while i<n//2 and k>mink[i]:
if s[i]=='9':
if s[n-1-i]!='9':
s[n-1-i]='9'
k-=1
elif s[n-1-i]=='9':
s[i]='9'
k-=1
elif k-2>=mink[i+1]:
s[i]=s[n-1-i]='9'
k-=2
else:
if s[i]!=s[n-1-i]:
s[i]=s[n-1-i]=max(s[n-1-i],s[i])
k-=1
i+=1
if i<n//2:
for j in range(i,n//2):
if s[j]>s[n-1-j]:
s[n-1-j]=s[j]
else:
s[j]=s[n-1-j]
elif n%2:
if k>0:
s[n//2]='9'
return ''.join(s) | true |
e075f457ae5c67afb31df270d6b7f946669a5412 | CiroIgnacio/Python_Curso | /Guía 2/ejercicio5_2_2020030707182401.py | 858 | 4.125 | 4 | """
Ejercicio 5: Crear un diccionario con los meses del año de la forma { 1: "enero"}. Desafío: lograr cambiar las claves. Pista: si imprimen
ítems del diccionario les crea una lista. Una vez que lo logren, imprimir el diccionario modificado.
"""
meses = {1: "enero",
2: "febrero",
3: "marzo",
4: "abril",
5: "mayo",
6: "junio",
7: "julio",
8: "agosto",
9: "septiembre",
10: "octubre",
11: "noviembre",
12: "diciembre"}
# Lo que había que hacer
meses_invertido = {}
for keys, values in meses.items():
meses_invertido[values] = keys
print(meses_invertido)
# Lo que entendí que había que hacer
i = 1
for keys in meses:
meses[f"Mes {i}"] = meses.pop(i)
i += 1
if i == 13:
break
print(meses)
| false |
b8e9a48964c61c33eedb0a2cf11b94c2345e75fd | stevekutz/python_iter_sort | /DailyCode Challenge/StairCase_n_steps.py | 2,614 | 4.53125 | 5 | """
There's a staircase with N steps, and you can climb 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase.
The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time,
you could climb any number from a set of positive integers X?
For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
Generalize your function to take in X.
"""
"""
It's always good to start off with some test cases. Let's start with small cases and
see if we can find some sort of pattern.
N = 1: [1]
N = 2: [1, 1], [2]
N = 3: [1, 2], [1, 1, 1], [2, 1]
N = 4: [1, 1, 2], [2, 2], [1, 2, 1], [1, 1, 1, 1], [2, 1, 1]
What's the relationship?
The only ways to get to N = 3, is to first get to N = 1, and then go up by 2 steps,
or get to N = 2 and go up by 1 step. So f(3) = f(2) + f(1).
Does this hold for N = 4? Yes, it does. Since we can only get to the 4th step
by getting to the 3rd step and going up by one, or by getting to the 2nd step and
going up by two. So f(4) = f(3) + f(2).
To generalize, f(n) = f(n - 1) + f(n - 2). That's just the Fibonacci sequence!
def staircase(n):
if n <= 1:
return 1
return staircase(n - 1) + staircase(n - 2)
Of course, this is really slow (O(2N)) — we are doing a lot of repeated computations!
We can do it a lot faster by just computing iteratively:
def staircase(n):
a, b = 1, 2
for _ in range(n - 1):
a, b = b, a + b
return a
Now, let's try to generalize what we've learned so that it works if you can take a
number of steps from the set X. Similar reasoning tells us that if X = {1, 3, 5},
then our algorithm should be f(n) = f(n - 1) + f(n - 3) + f(n - 5).
If n < 0, then we should return 0 since we can't start from a negative number of steps.
def staircase(n, X):
if n < 0:
return 0
elif n == 0:
return 1
else:
return sum(staircase(n - x, X) for x in X)
"""
# N = 4: [1, 1, 2], [2, 2], [1, 2, 1], [1, 1, 1, 1], [2, 1, 1]
list_ways = []
def staircase(n, X):
global list_ways
cache = [0 for _ in range(n + 1)]
print(f' orig cache {cache}')
cache[0] = 1
print(x)
list_ways.append(cache)
for i in range(1, n + 1):
cache[i] += sum(cache[i - x] for x in X if i - x >= 0)
return cache[n]
x = 4 # how many steps
X = {1,2} # how many steps you can take at a time
print(staircase(x, X)) # 5
print(list_ways) | true |
57451fd1823f0f46729fa863c6f2fcb9964d9ff2 | pdenapo/programitas-algebraI | /Python/2020/Euclides.py | 1,189 | 4.15625 | 4 | #!/usr/bin/env python3
# Programa recursivo en Python 3 para calcular el máximo común divisor
# usando el algoritmo de Euclides
# Este programa tiene solamente propósitos didácticos
# (es para mis alumnos de Algebra I).
# (C) 20014-2016 Pablo De Nápoli <pdenapo@dm.uba.ar>
# Este programa es software libre, y usted puede redistribuirlo o
# modificarlo libremente bajo los términos de la
# GNU General Public Licence (Licencia Pública General), versión 3
# o cualquier versión posterior,
# publicada por la Free Software Foundation. Vea:
#
# http://www.gnu.org/copyleft/gpl.html
import argparse
def mcd(a,b):
if b>a:
return mcd(b,a)
if b==0:
print ("¡El algoritmo de Euclides termina!")
print ("El máximo común divisor es",a)
return a
else:
k, r= divmod(a,b)
print(a,"=",k,"*",b,"+",r)
print ("mcd(",a,",",b,")=mcd(",b,",",r,")")
return mcd(b,r)
parser = argparse.ArgumentParser(description='Calcula el máximo común divisor usando el algoritmo de Euclides')
parser.add_argument("a", type=int)
parser.add_argument("b", type=int)
args=parser.parse_args()
print("Calculamos el máximo común divisor entre ",args.a," y ",args.b)
mcd(args.a,args.b)
| false |
4653cca4991b2dff08ed3839f4dddeea86d7a422 | JNewberry/variables | /revision task 1.3.py | 334 | 4.25 | 4 | #John Newberry
#15/09/14
first_integer = int(input("Please enter the first integer: "))
second_integer = int(input("Please enter the second integer: "))
answer_one = (first_integer // second_integer)
answer_two = (first_integer % second_integer)
print("the answer is {0} with a remainder of {1}!".format(answer_one,answer_two))
| true |
e685850b9016c5437a4e3718f3e64312dd858208 | ab1995/Python | /Assignment_Session3/LoginTime.py | 269 | 4.125 | 4 | import datetime
time = datetime.datetime.strptime(input('Input Time in HHMM Format: '), "%H%M")
if time.hour>=0 and time.hour<12:
print("Good Morninig!:)")
elif time.hour>12 and time.hour<=6:
print("Good Afternoon")
elif time.hour>6:
print("Good Evening") | true |
19fe55aeb613241c63f4f61f1000d810404bdd6b | risomt/codeeval-python | /16.py | 1,291 | 4.21875 | 4 | """
Challenge Description:
Write a program to determine the number of 1 bits in the internal representation of a given integer.
Input sample:
The first argument will be a text file containing an integer, one per line. e.g.
10
22
56
Output sample:
Print to stdout, the number of ones in the binary form of each number.
e.g.
2
3
3
"""
from sys import argv
with open(argv[1]) as data:
for line in data.readlines():
# it seems like cheating to use bin() function so this is the hard way
# parse out the number to generate in binary
number = int(line.strip())
binary = []
# explanation: http://www.wikihow.com/Convert-from-Decimal-to-Binary #2
# the remainder (mod) of the current number and the base (2) represents the
# opposite value in binary (hence the reverse at the end)
while True:
if number == 0:
break
else:
# determine binary representation of current number
binary.append(number % 2)
# divide number by half and continue until we reach 0
number = number / 2
# reverse to complete algorithm
#binary.reverse()
# we can skip this because order of bits doesn't change result
# count number of 1s
# we could use list.count(1) here
count = 0
for bit in binary:
if bit == 1:
count += 1
print count | true |
1eb6ef2616ac5b738eb93a7a7024cf9c07dd7203 | risomt/codeeval-python | /92.py | 676 | 4.25 | 4 | """
Challenge Description:
Write a program which finds the next-to-last word in a string.
Input sample:
Your program should accept as its first argument a path to a
filename. Input example is the following
some line with text
another line
Each line has more than one word.
Output sample:
Print the next-to-last word in the following way.
with
another
"""
from sys import argv
with open(argv[1]) as data:
for line in data.readlines():
#split words apart by space and then output second to last
words = line.strip().split()
print words[-2]
| true |
82162235e6c3df216951a1b59f44963b970527a8 | risomt/codeeval-python | /35.py | 1,229 | 4.3125 | 4 | """
Challenge Description:
You are given several strings that may/may not be valid emails. You should write a regular expression that determines if the email id is a valid email id or not. You may assume all characters are from the english language.
Input sample:
Your program should accept as its first argument a filename. This file will contain several text strings, one per line. Ignore all empty lines. E.g.
foo@bar.com
this is not an email id
admin#codeeval.com
good123@bad.com
Output sample:
Print out 'true' (all lowercase) if the string is a valid email. Else print out 'false' (all lowercase). E.g.
true
false
false
true
"""
from sys import argv
from re import compile, match
with open(argv[1]) as data:
# build an email validation regex. Not sure this is 100% accurate.
re_email = compile('^([a-zA-Z0-9._%-+]+)@([a-zA-Z0-9._%-+]+)\.([a-zA-Z]{2,6})$')
# check each email in file. If valid, print 'true', else print 'false'
for line in data.readlines():
if re_email.match(line.strip()):
print 'true'
else:
print 'false'
| true |
0fd7b45675cfd1d9563e3ec8fb75aa0eb53069a4 | Tejmeister/design-patterns | /creational_design_patterns/Singleton/singleton.py | 1,523 | 4.4375 | 4 | class SingletonMeta(type):
"""
The Singleton class can be implemented in different ways in Python. Some
possible methods include: base class, decorator, metaclass. We will use the
metaclass because it is best suited for this purpose.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
"""
Possible changes to the value of the `__init__` argument do not affect
the returned instance.
"""
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
def __init__(self, name) -> None:
self.name = name
def some_business_logic(self):
"""
Finally, any singleton should define some business logic, which can be
executed on its instance.
"""
def __str__(self) -> str:
return self.name
class MotherBoard(metaclass=SingletonMeta):
def __init__(self, name) -> None:
self.name = name
def some_business_logic(self):
"""
Finally, any singleton should define some business logic, which can be
executed on its instance.
"""
def __str__(self) -> str:
return self.name
if __name__ == "__main__":
# The client code.
s1 = Singleton("Tejas")
s2 = Singleton("Parmar")
print(s1)
print(s2)
if id(s1) == id(s2):
print("Singleton works, both variables contain the same instance.")
else:
print("Singleton failed, variables contain different instances.")
print(SingletonMeta._instances)
m = MotherBoard("Intel")
print(SingletonMeta._instances) | true |
0f66c19183deaf131e55ee8aad822770d2f67180 | samuelcm/estrutura_sequencia | /produto2.py | 882 | 4.28125 | 4 | #Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
#o produto do dobro do primeiro com metade do segundo .
#a soma do triplo do primeiro com o terceiro.
#o terceiro elevado ao cubo.
contagem = 1
while contagem <= 1:
num1 = input("digite um numero inteiro\n")
try:
num1 = int(num1)
except:
print ("digite um numero valido")
continue
num2 = input("digite um numero inteiro\n")
try:
num2 = int(num2)
except:
print ("digite um numero valido")
continue
contagem += 1
cont = 1
while cont <= 1:
num3 = input("digite um numero real\n")
try:
num3 = float(num3)
except:
print ("digite um numero valido")
continue
cont += 1
soma = 3*num1 + num3
produto = (num1*2) * (num2/2)
cubo = num3**3
print(produto, soma, cubo)
#int1 = int(int1)
| false |
8c4dc7521c718ec4f96395a8c321ece0c243ab14 | samuelcm/estrutura_sequencia | /dobro_area.py | 207 | 4.15625 | 4 | #Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
lado = float(input("medida do lado do quadrado: "))
area = lado *2
dobro = area*2
print(dobro)
| false |
58151ebd42beb1e17be013ed9e4f5471e9155390 | nomisfailla/FIT1045 | /week2/2.b_sum.py | 242 | 4.25 | 4 | start = input("where should i start? ")
stop = input("where should i stop? ")
start = int(start)
stop = int(stop)
summation = 0
for i in range(start, stop+1):
summation = summation + (3 * i)
print("result: " + str(summation))
| true |
e1acf1d386a5a68cf2c5cc6aaed07aa48148cd94 | advaith-unnikrishnan/Getting-started-with-Python | /Basic Programs/stack.py | 846 | 4.21875 | 4 | """
Program: Implement stack using Python, it can be implemented using lists in python.
Instead of push() we can use append()
We can also use pop() function along with lists
Author:Advaith
"""
stack=[]
size=(int)(input("Enter the size of the stack "))
def push():
if size==len(stack):
print("STACK OVERFLOW")
else:
n=(int)(input("Enter the element "))
stack.append(n)
def pop():
if len(stack)==0:
print("STACK UNDERFLOW")
else:
print("Popped item is ",stack.pop())
def display():
print("The current stack is:")
for i in range(len(stack)-1,-1,-1):
print(stack[i])
while 1:
print("Menu")
print("1.Push")
print("2.Pop")
print("3.Display")
print("4.Exit")
ch=(int)(input("Enter your choice "))
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
display()
elif ch==4:
exit(0)
else:
print("Wrong Choice ")
| true |
fa53aa07d0368db674ccc2d76f7bfa2de0000590 | AlyssaHong/Self_Paced-Online | /students/john_rogers/lesson03/strformat_lab.py | 1,291 | 4.375 | 4 | #!/usr/bin/env python3
"""
String formatting exercises.
Author: JohnR
Version: .0
Notes:
"""
def main():
"""
Core script logic.
:return:
"""
pass
def task_1():
"""
Take tuple (2, 123.4567, 10000, 12345.67) and produce the below:
'file_002 : 123.46, 1.00e+04, 1.23e+04'
:return: Return the results of the changed tuple.
"""
pass
def task_2():
"""
Take in results from task_1 but display using an alternate format method.
:return: None
"""
pass
def task_3():
"""
Rewrite "the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3)" to take
an arbitrary number of values.
:return:
"""
pass
def task_4():
"""
Given a 5 element tuple (4, 30, 2017, 2, 27) use string formatting
to print '02 27 2017 04 40'
:return: None
"""
pass
def task_5():
"""
Use f-strings; Given the 4 element list ['oranges', 1.3, 'lemons', 1.1]
write an f-string that will display 'The of an orange is 1.3 and the
weight of a lemon is 1.1'.
Change the f-string so that is displays the names of the fruit in
uppercase and weight 20% higher.
:return: None
"""
pass
def task_6():
"""
tbd
:return: tbd
"""
pass
if __name__ == '__main__':
main() | true |
63de41ebb055ea21bec787bb11ecb2dac654b202 | paulbmouton/python-practice | /string_methods.py | 568 | 4.28125 | 4 | # String Methods
# prints length of string
parrot = "Norwegian Blue"
print len(parrot)
# prints string in all lowercase
print "Norwegian Blue".lower()
# prints string in all upper
print "Norwegian Blue".upper()
# methods with dot notation only work with strings
# prints non-strings as strings
# numbers are never strings unless made one
pi = 3.14
print str(pi)
# non-strings can be made strings with quotes
pil = "3.144"
print pil
# Test
print "The value of pi is around " + str(pi)
# leave space after printed string for non-string to appear correctly
| true |
45ac436f5b5c4e765526fa2e5bdf6ac2bdd98fdb | isaac-friedman/interview_cake | /course/02_chapter2_hashing_and_dictionaries/permutation_palindrome.py | 1,128 | 4.1875 | 4 | def permutation_palindrome(instring):
"""
Friedman's Something Or Other of Palindromes:
a collection of characters can be arranged (permuted) into a palindrome if
and only if there is an even number of each character in the collection or
there is an even number except for one character which only occurs once
"""
instring = instring.replace(" ","")
letter_dict = {}
# Fill our dictionary
for char in instring:
if char in letter_dict:
letter_dict[char] += 1
else:
letter_dict[char] = 1
# Check that our dictionary has the right number of the right letters
unique_chars = 0
for i in letter_dict:
if letter_dict[i] % 2 == 0:
pass
elif letter_dict[i] > 1: # The string is assymetrical
return False
else: # i == 1
if unique_chars > 1:
return False
else:
unique_chars += 1
return True
pass_text = "a man a plan a canal panama"
fail_text = "adam aint madam"
print(permutation_palindrome(pass_text))
| true |
de470ea20490a21a145eeb812ce64d5221d985c8 | nushrathumaira/Fall2017102 | /newlab3/lab3sol/is_sorted.py | 343 | 4.15625 | 4 | import sys
# python is_sorted.py <input_file>
with open(sys.argv[1], "r") as numbers:
arr = []
for line in numbers.readlines():
arr.append(int(line))
if all(a <= b for a,b in zip(arr[:-1], arr[1:])):
print("List of " + str(len(arr)) + " integers is sorted!\n")
else:
print("List is not sorted...\n")
| true |
ba5382995d3fc1a855df662c4f0cb19f170512e1 | green-fox-academy/Atis0505 | /week-02/day-04/substrlist.py | 669 | 4.28125 | 4 | # Find the substring in the list
# Create a function that takes a string and a list of string as a parameter
# Returns the index of the string in the list where the first string is part of
# Returns -1 if the string is not part any of the strings in the list
# Example
# input: "ching", ["this", "is", "what", "I'm", "searching", "in"]
# output: 4
string_list = ["this", "is", "what", "I'm", "searching", "in"]
key_string = "this"
def check_string(word, str_list):
index = -1
for word_from_list in str_list:
index += 1
if not -1 == word_from_list.find(word):
print(word_from_list.find(word))
check_string(key_string,string_list) | true |
0f991d419053cae6a90fc717a4d95213498cd6c9 | green-fox-academy/Atis0505 | /week-02/day-02/reverse_list.py | 307 | 4.1875 | 4 | # - Create a variable named `aj`
# with the following content: `[3, 4, 5, 6, 7]`
# - Reverse the order of the elements in `aj`
# - Print the elements of the reversed `aj`
# aj = list(reversed(aj))
aj = [3, 4, 5, 6, 7]
for i in range(0,int((len(aj)/2))):
aj[0+i],aj[-1-i] = aj[-1-i],aj[0+i]
print(aj)
| true |
41b02a3a3f36a56ca677405e367ea60f24ed304e | green-fox-academy/Atis0505 | /week-03/day-01/write_single_line.py | 494 | 4.1875 | 4 | # Open a file called "my-file.txt"
# Write your name in it as a single line
# If the program is unable to write the file,
# then it should print an error message like: "Unable to write file: my-file.txt"
file_address = "my_file.txt"
def write_in_file(file_text):
try:
my_file = open(file_text, "w")
my_file.writelines("Kőröm Attila")
my_file.close()
print("Done!")
except IOError:
print("Unable to write file, ",file_text)
write_in_file(file_address) | true |
e8cae921095a0f1141339b2de34f3cb116b7333d | green-fox-academy/Atis0505 | /week-02/day-03/is_in_the_list.py | 775 | 4.1875 | 4 | # Check if list contains all of the following elements: 4,8,12,16
# Create a function that accepts list_of_numbers as an input
# it should return "True" if it contains all, otherwise "False"
list_of_numbers = [2, 4, 6, 8, 10, 12, 14, 16]
check_numbers = [4,8,12,16]
equal_num = 0
for n in list_of_numbers:
for m in check_numbers:
if equal_num < len(check_numbers):
if n == m:
equal_num+=1
if equal_num == len(check_numbers):
print("True")
else:
print("False")
def is_all_element_in_the_list(need_to_contains, list_of_numbers):
for element in need_to_contains:
if not element in list_of_numbers:
return False
return True
print(is_all_element_in_the_list(check_numbers,list_of_numbers)) | true |
a8bc411483bd9b2fc4b383bda40d802a589cf6c6 | green-fox-academy/Atis0505 | /week-04/day-03/fibonacci/fibonacci.py | 353 | 4.21875 | 4 | def fibonacci_counter(int_index):
if int_index == None:
return None
else:
if type(int_index) is not int:
return 0
if int_index == 0:
return 0
elif int_index == 1:
return 1
else:
return fibonacci_counter(int_index-1) + fibonacci_counter(int_index-2)
| false |
ad229dc6d616cb83584ec49d9087dd8686e73bbe | LeonardoMelloTrindade/Codigos-Python | /Calculadoraa.py | 1,544 | 4.3125 | 4 | print('-----CALCULADORA COM WHILE-----')
from time import sleep
import emoji
num1 = float(input('Digite o primeiro número: '))
num2 = float(input('Digite o segundo número: '))
operador = 0
#SO VAI ENCERRAR QUANDO O OPERADOR RECEBER O VALOR 5
while operador != 5:
sleep(0.8)
operador = int(input(('''Digite um número para realizar uma operação:
[ 1 ] - Adição
[ 2 ] - Multiplicação
[ 3 ] - Maior e Menor
[ 4 ] - Novos números
[ 5 ] - Encerrar operação
Qual o operador desejado? ''')))
#ESTRUTURA DE REPETIÇÃO DOS OPERADORES
#SOMAR
if operador == 1:
print('{:.2f} + {:.2f} = {:.2f}'.format(num1, num2, num1 + num2))
#MULTIPLICAR
elif operador == 2:
print('{:.2f} x {:.2f} = {:.2f}'.format(num1, num2, num1 * num2))
#MAIOR E MENOR NÚMERO
elif operador == 3:
if num1 > num2:
print('{} é maior que {}.'.format(num1, num2))
elif num2 > num1:
print('{} é maior que o {}.'.format(num2, num1))
elif num1 == num2:
print('Ambos são iguais.')
else:
print('ERRO, TENTE NOVAMENTE!!!')
#INSERIR NOVOS NÚMEROS
elif operador == 4:
num1 = float(input('Digite o primeiro número novamente: '))
num2 = float(input('Digite o segundo número novamente: '))
elif operador == 5:
print(emoji.emojize("FIM DO PROGRAMA, OBRIGADO POR UTILIZAR :sparkling_heart: :sparkling_heart: :sparkling_heart:", use_aliases=True))
| false |
ce591ef961a41edff8bb1976f014b278f8e2adb0 | adyprajwal/python | /POP/fibo.py | 335 | 4.15625 | 4 | import time
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
start_time = time.clock()
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))
end_time = time.clock()
print("Execution time: %s"%(end_time-start_time))
| true |
ddafdcd7e9e6d7daa7a58b956c56f72f40c12e9b | adyprajwal/python | /POP/prime.py | 253 | 4.15625 | 4 | #Print Prime Numbers below input value
num = int(input("Enter a number below which you want to find the prime numbers: "))
def prime_num(x):
for i in range(2, x):
for b in range(2, i):
if i % b == 0:
break
else:
print(i)
prime_num(num) | true |
b4d8dac163b1357fd3213e5b6b65c64f2f25f8fa | javiapp/GADS9-NYC-Spring2014-Students | /lab_submissions/lab01/dgottipati/Car.py | 1,229 | 4.5625 | 5 |
# Creates a new Class for Car
class Car():
""" This is the initialization of the Car class
Defaults to the model = Ford; wheels = 4 """
def __init__(self, model='Ford', wheels=4):
self.model = model # assigning the model passed into class to model variable
self.running = False # assigning the value of running to False, as the car is initially not running
self.wheels = wheels # assigning the value of the wheels passed in to the wheels variable of the object
"""This snippet checks to see if the wheeks are less than zero.
If the wheels are less than 0, it prints an error message and sets the wheels = 0 """
if self.wheels < 0:
print "You can't have negative wheels on a car."
self.wheels = 0
def start(self):
if self.running != True:
print 'The car started!'
self.running = True
else:
print 'The car is already running!'
def stop(self):
if self.running == True:
print 'The car stopped!'
self.running = False
else:
print 'The car was not running!'
ford = Car()
nissan = Car(model = 'Nissan', wheels=-2)
ford.running
ford.start()
ford.running
nissan.running
nissan.stop()
| true |
b01f5c369838e5cd267ff7eb3ecf3d9ccbe35a3f | PeterSchell11/Python---Beginnings | /Lists.py | 1,353 | 4.53125 | 5 | #Lists
#A list is collection which which is ordered and changeable
#written with square brackets[]
thisList = ["apple", "banana", "cherry"]
print (thisList)
#"" '' makes no difference ; will print the same
food = ['muffin', 'chips', 'coke']
#Repitation Operator
# symbol *
value = [1,2,3,4]*5
print(value)
#iterating over a List with the for loop
for x in [1,2,3,4,5]:
print(x)
#positive indexing and negative indexing
myList = [4,21.2,'hi']
print (myList)
print (myList[0])#prints first on the list
print (myList[1])#
print (myList[2])#prints second on the list
print (myList[-1])#prints last item on the list
print (myList[-2])#prints second on the list
print (myList[-3])#prints third last item on the list
#List length
print(len(myList))#prints number of items in list
#using loop to iterate by index over list
fruits =['apple','banana','cherry']
for index in range (len(fruits)):
print (fruits[index])
#Lists are Mutable
#elements are changable
numbers=[1,2,3,4]
print (numbers)
numbers[0]=99
numbers[-1]=12
print(numbers)
#if you want to fill list with indexing, you need to creat list first
nums=[0]*5
print(nums)
for index in range(len(nums)):
nums[index]=float(input('enter number '))
print (nums)
#combining two lists
list1=[1,2,3]
list2=[4,5,6]
list3=list1+list2
print(list3)
| true |
06735e74125c0a1a2ffac437457a61edab469efc | anarvaez81/tratamientodatos2 | /holamundo2.py | 432 | 4.21875 | 4 | print ("Hola Mundo")
numero1 = int(input("Introduce un número: "))
numero2 = int(input("Introduce otro número: "))
print ("La suma de ", numero1, "más ", numero2, " es ", numero1 + numero2)
print ("Strings - Cadenas de texto")
cadena1 = "Esto es una prueba de cadenas de texto en Python por ProyectoA"
cadena3 = "Concatenaremos y extraeremos texto de estas cadenas"
print ("Concatenamos cadena1 y cadena2")
print (cadena1,cadena3)
| false |
860336f358bb27d1451b7dac0a3fccf373c8bcee | niyogakiza/april-2020-machine-learning | /datascale/datascale.py | 1,131 | 4.15625 | 4 | # Data scaling The values of each feature in a dataset can
# vary between random values. So, sometimes it is important to scale them so that this becomes a level playing field.
# Through this statistical procedure, it's possible to compare identical variables belonging to different
# distributions and different variables.Remember, it is good practice to rescale data before training a machine
# learning algorithm. With rescaling, data units are eliminated, allowing you to easily compare data from different
# locations.
from sklearn import preprocessing
import numpy as np
data = np.array([[3, -1.5, 2, -5.4], [0, 4, -0.3, 2.1], [1, 3.3, -1.9, -4.3]])
data_scaled = preprocessing.MinMaxScaler(feature_range=(0, 1))
data_scaled = data_scaled.fit_transform(data)
print("Min: ", data.min(axis=0)) # [ 0. -1.5 -1.9 -5.4]
print("Min: ", data.max(axis=0)) # [3. 4. 2. 2.1]
# display the scaled array
print(data_scaled)
# [[1. 0. 1. 0. ]
# [0. 1. 0.41025641 1. ]
# [0.33333333 0.87272727 0. 0.14666667]]
| true |
dffad1c47fd0e663ba222abab89ef690ba679775 | patkhai/LeetCode-Python | /LeetCode/TopKFrequentWords.py | 1,256 | 4.3125 | 4 | '''
Use lambda to sort the dictionary in desc order based on words frequency and if frequency are equal then sort dictionary in asc order based on the word alphabet.
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
'''
#O(nlogn), O(N)
def topKFrequent(words,k):
dict = {}
for x in words:
if x in dict:
dict[x] += 1
else:
dict[x] = 1
res = sorted(dict, key=lambda x: (-dict[x], x))
return res[:k]
w = ["i", "love", "leetcode", "i", "love", "coding"]
k = 2
print(topKFrequent(w,k)) #['i', 'love']
| true |
377af0c3c505628631aa0f7a07af5851183e072f | patkhai/LeetCode-Python | /LeetCode/SortCharactersByFrequency.py | 983 | 4.28125 | 4 | '''
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input:
"cccaaa"
Output:
"cccaaa"
Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input:
"Aabb"
Output:
"bbAa"
Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
'''
#O(nlogk), O(n)
from collections import Counter
def frequencySort(s):
# Count the occurence on each character
count = Counter(s)
new_str = []
for letter, freq in count.most_common():
new_str.append(letter * freq)
return ''.join(new_str)
s = "tree"
print(frequencySort(s)) # "eert"
| true |
68fdecab2ebb991f9e335455c8ecd7c193169950 | patkhai/LeetCode-Python | /LeetCode/Find_Haystack_Needles.py | 474 | 4.28125 | 4 |
'''
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
'''
def strStr(haystack,needle):
if needle == None:
return 0
if needle in haystack:
return haystack.index(needle)
return -1
print(strStr("aaaaa", "bba"))#-1
print(strStr("hello", "ll"))# 2 | true |
ace3543fbedb2e5c85d2c833d8fa1c2cea6e1196 | patkhai/LeetCode-Python | /LeetCode/MinimumHeightTree.py | 1,733 | 4.25 | 4 | '''
For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.
Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example 1 :
Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
Output: [1]
Example 2 :
Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
Output: [3, 4]
'''
def findMinHeightTrees(n, edges):
tree = [set() for _ in range(n)]
for x, y in edges:
tree[x].add(y)
tree[y].add(x)
queue = []
for i in range(n):
if len(tree[i]) <= 1:
queue.append(i)
while queue:
new_queue = []
for node in queue:
for nxt in tree[node]:
tree[nxt].remove(node)
if len(tree[nxt]) == 1:
new_queue.append(nxt)
if not new_queue:
return queue
queue = new_queue
n = 6
edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
print(findMinHeightTrees(n , edges)) | true |
a3beb52c4350b2fcc5553fab299fd7cfa4444f61 | NyxSloth/homework-5-NyxSloth | /listy_lo.py | 1,314 | 4.3125 | 4 |
if __name__ == "__main__":
# Create a list named food with two elements 'rice' and 'beans'.
food = ['rice','beans']
# Append the string 'broccoli' to food using .append().
food.append('broccoli')
print(food)
# Add the strings 'bread' and 'pizza' to food using .extend().
food1 = ['bread','piza']
food.extend(food1)
print(food)
# Print the first two items in the food list using print() and slicing notation.
print(food[0:2])
# Print the last item in food using print() and index notation.
print(food[-1])
# Create a list called breakfast from the string "eggs,fruit,orange juice" using the split() method.
bfast = "eggs,fruit,orange juice"
breakfast = bfast.split(',')
print(breakfast)
# Verify that breakfast has 3 elements using the len built-in.
print(len(breakfast))
# prompts the user for a floating-point value until they enter stop. Store their entries in a list, and then find the average, min, and max of their entries and print them those values.
user_list = []
user_input = 'start'
while True:
user_input = input('Enter a floating-point value. When done, enter stop. ')
if user_input == 'stop':
break
value = float(user_input)
user_list.append(user_input)
print(user_list)
| true |
ef3830a83df005975acb514f84d3272bcd0eeab2 | mcflurryXD96/Week-Two-Assignment | /Convert_From_F_to_C.py | 332 | 4.28125 | 4 | #
__author__ = 'Daniel McMurray'
# CIS 125
# Convert Fahrenheit to Celsius
#
# This program prompts the user for a temperature in Fahrenheit, converts it to Celsius, and prints out the results.
F = eval(input("Please enter a temp in Fahrenheit: "))
C = (F-32) * 5 / 9
print("The temp ", F, " in Fahrenheit is equal to ", C, " Celsius")
| true |
71810e5f970772fd1e93ef4a600cad3abbad62bd | chen-chien-lung/Python-100-challenge | /22.py | 649 | 4.28125 | 4 | # Question:
# Write a program to compute the frequency of the words from the input.
# The output should output after sorting the key alphanumerically.
# Suppose the following input is supplied to the program:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Then, the output should be:
# 2:2
# 3.:1
# 3?:1
# New:1
# Python:5
# Read:1
# and:1
# between:1
# choosing:1
# or:2
# to:1
from collections import OrderedDict
freq = {}
words = input().split(" ")
for word in words:
freq[word] = freq.get(word, 0)+1
keys = freq.keys()
d = OrderedDict.fromkeys(keys)
for w in d:
print("%s:%d" % (w, freq[w])) | true |
8b3674af6868f94da82abf483d1df0404c026dd1 | KbrehmCoding/Coding-Languages-Tests | /quiz3/python/quizQ3.py | 1,388 | 4.46875 | 4 | # 3. Write a program to calculate multiplication and division of two numbers (input from user).
# look up pyhon code to take user input in the command line and use it in math functions
# num1 = int(input("Please input first number: "))
# num2 = int(input("Please input second number: "))
# def multiply():
# multi = num1 * num2
# sumMulti = num1 + " Multiplied by " + num2 + " is " + multi
# print(sumMulti)
# def divide():
# divi = num1 / num2
# sumDivi = num1 + " Divided by " + num2 + " is " + divi
# print(sumDivi)
# operator = input("Would you like to multiply these numbers, or divide them? : ")
# while operator != "multiply" or operator != "divide":
# if operator == "multiply":
# multiply()
# elif operator == "divide":
# divide()
num1 = int(raw_input("Please input first number: "))
num2 = int(raw_input("Please input second number: "))
def multiply():
print "{} multiplied by {} is {}".format(num1, num2, num1 * num2)
def divide():
print "{} divided by {} is {}".format(num1, num2, num1 / num2)
operator = raw_input("Would you like to multiply these numbers, or divide them? : ")
while operator != "multiply" and operator != "divide":
operator = raw_input("Would you like to multiply these numbers, or divide them? : ")
if operator == "multiply":
multiply()
elif operator == "divide":
divide()
| true |
5ae56fd8fecaa3cd13dae1952fe3c50d8095a6d4 | caikunqiao/python | /4_numbers.py | 571 | 4.40625 | 4 | #range不能生成尾数
#for value in range(1,5):
# print(value)
#numbers = list(range(1,6))
#print(numbers)
#odd_numbers = list(range(1,12,2))
#print(odd_numbers)
#squares = []
#for value in range(1,6):
## square = value**2
## squares.append(square)
# squares.append(value**2)
#print(squares)
#a = min(squares)
#b = max(squares)
#c = sum(squares)
#print(a,b,c)
#squares = [value**2 for value in range(1,6)]
#print(squares)
#threes = list(range(3,31))
#for value in threes:
# print(value)
cubics = [value**3 for value in range(1,11)]
print(cubics) | true |
b148dd7277c0a7fcb6ee08414f89901a64ad3455 | seendsouza/teaching | /Python/3-Loops/loops.py | 2,945 | 4.59375 | 5 | """
A collection of loops for practice
"""
# For Loops
print("For Loops")
# Prints each letter in the string "banana"
for x in "banana":
print(x)
# Prints each member of the list (fruits)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# Prints each member of the list until "banana" is printed
# It then breaks out of the loop, so "cherry" is not printed
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
"""
Since numbers start at 0, prints 0 to (6-1) or 0 to 5 (number of numbers
printed is 6)
"""
for x in range(6):
print(x)
# Prints 2 to 5
for x in range(2, 6):
print(x)
# Prints 2 to 30 and increments by 3 each time instead of 1
for x in range(2, 30, 3):
print(x)
# When done, it will print "Finally finished!"
for x in range(6):
print(x)
else:
print("Finally finished!")
# Adjective and fruit list
adjective = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
# For every adjective, it prints every fruit in the list above after it
for x in adjective:
for y in fruits:
print(x, y)
for i, value in enumerate(fruits):
print(i, value)
for i, value in enumerate(fruits, 1):
print(i, value)
# While Loops
print("\n\nWhile Loops")
true_variable = True
"""
These are infinite loops because true_variable is always true (until you set
it to be false)
Infinite loops are usually bad because they run forever
If they store data (not like this one) in memory or on drive, this will be
infinitely adding data to the computer (which could lead to RAM overflow
or running out of disk space)
"""
"""
while true_variable == True:
print("I'm in an infinite loop")
while true_variable:
print("I'm in an infinite loop again")
"""
x = -5
while x < 0:
x += 1
print("I'm incrementing by 1 and I'm at {}".format(x))
# Recursion
print("\n\nRecursion")
# Uses itself
def tri_recursion(k):
if(k > 0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
tri_recursion(6)
"""
Explanation with 6 as an example:
k = 6
k > 0, so result is 6 + 5 + 4 + 3 + 2 + 1 + 0 = 21
That is the last result, but what about the previous results?
Remember that recursion uses itself, so everytime it calls itself, it needs
to execute the whole function
The result is only when k is 1 because when k = 0, k !> 0 and therefore
the function does not print anything, but returns the result as 0
(because of the else statement)
I like to think of it as going backwards from there, so result = 1 + 0 = 1
and it is printed and returned
Then you have the next k, which is 2, so 2 + 1 = 3
Then you have the next k, which is 3, so 3 + 3 = 6
Then you have the next k, which is 4, so 4 + 6 = 10
Then you have the next k, which is 5, so 5 + 10 = 15
Then you have the next k, which is 6, so 6 + 15 = 21
It prints the numbers: 1, 3, 6, 10, 15, 21 as a result
"""
| true |
136746c2da5ae36ec99eb4000f24d5ea8b532f02 | DaryaIvasyuk253/python_7_10 | /hw_11_13.py | 1,267 | 4.1875 | 4 | import math
#task_11
#---------------------------------
def degrees_to_radians (value):
return math.cos(math.radians(value))
result1 = degrees_to_radians (60)
result2 = degrees_to_radians(45)
result3 = degrees_to_radians(40)
print('Значение косинусов улов в градусах будет равно в радианах: %.1f' % result1,
'%.1f' % result2, '%.1f' % result3)
#task_12
#---------------------------------
def sum_of_all_numerals (numeral):
sum = (numeral // 100) + (numeral % 100 // 10) + (numeral % 10)
return sum
result = sum_of_all_numerals(257)
print('Сумма цифр трехзначного числа равна:', result)
#task_13
#----------------------------------
def right_triangle_perimeter_and_square(cathetus_1, cathetus_2):
hypotenuse = math.sqrt(pow(cathetus_1, 2) + pow(cathetus_2, 2))
triangle_perimeter = hypotenuse + cathetus_1 + cathetus_2
triangle_square = 1/2 * cathetus_1*cathetus_2
return triangle_perimeter, triangle_square
result_1, result_2 = right_triangle_perimeter_and_square(5,6)
print('Периметр и площадь прямоугольного треугольника равно: ' '%.1f'% result_1, 'см. и', int(result_2), 'см.')
| false |
0defce5fe714fa7e7175ad2fb228137e7e3af1ea | sakshi9401/other_py_programs | /if_elif_else.py | 351 | 4.1875 | 4 | marks = int(input("enter your marks :\n"))
if marks>=90 :
print("grade : exellent")
elif marks>=80 and marks<70:
print("grade : A")
elif (marks>=70 and marks<80):
print("grade : B")
elif marks>=60 and marks<70 :
print("grade : c")
elif marks>=50 and marks<60 :
print("grade : D")
else :
print("grade : F") | false |
59fde4b55d3b82e00ae19eaf948a918f2a49a009 | laxbista/Python-Practice | /String_Excercises/q9.py | 396 | 4.21875 | 4 | # Exercise Question 9: Given a string, return the sum and average
# of the digits that appear in the string, ignoring all other characters
import re
str1 = "English = 78 Science = 83 Math = 68 History = 65"
total = 0
List = [int(i) for i in str1.split() if i.isdigit()] # Using List comprehension
for num in List:
total += num
average = total / len(List)
print(total, average)
| true |
55c65f4d3f556b15cf0cb4b571a479dbe226a787 | laxbista/Python-Practice | /String_Excercises/q3.py | 337 | 4.21875 | 4 | # Exercise Question 3: Given 2 strings, s1, and s2 return a new string made of the first,
# middle and last char each input string
def newString(s1, s2):
Mids1 = len(s1)//2
Mids2 = len(s2)//2
new_String = s1[:1] + s2[:1] + s1[Mids1] +s2[Mids2] + s1[-1] +s2[-1]
print(new_String)
newString("America", "Japan")
| true |
50c92e5259c2bed1d0bb310f2268e69c720edb96 | BryanMRoss/python_playground | /function_sample.py | 369 | 4.25 | 4 | # Function example in a loop. This will print a table of celcius temps between
# 0 and 100 in increments of 10
def convert_to_fahrenheit(celcius):
"""this converts the celcius number to fahrenheit"""
f = 9.0/5.0 * celcius + 32
return f
for celcius in range(0, 101, 10):
print("Celcius value", celcius, "\t", "=", "\t", convert_to_fahrenheit(celcius))
| true |
874c6e5da893d84af60233a0ec83f60209a76567 | douglasbolis/prog_1 | /roteiro_6/exerc_3.py | 897 | 4.25 | 4 | # 3. Crie uma func˜ao que recebe como entrada uma lista de listas e verifica se a entrada corresponde
# a uma matriz. Uma lista de listas so e uma matriz quando todas as listas internas possuırem o
# mesmo tamanho.
def f_verificaMatriz(mat):
ehMatriz, tam = False, 0
tam = len(mat[0])
for lin in range(len(mat)):
if (tam == len(mat[lin])):
ehMatriz = True
else:
ehMatriz = False
#fim if
#fim for
return ehMatriz
#fim funcao
def f_imprimeMatriz(mat):
for lin in mat:
for el in lin:
print('%d ' %(el), end="");
#fim for
print()
#fim for
#fim funcao
def main():
matriz = [[2], [1, 3], [3, 9, 1], [1, 3, 7, 1]]
ehMatriz = f_verificaMatriz(matriz)
print("a lista de listas\n")
f_imprimeMatriz(matriz)
if (ehMatriz):
print("\neh uma matriz")
else:
print("\nnao eh uma matriz")
#fim if
return 0
#fim main
if __name__ == '__main__':
main()
#fim if
| false |
6f06672b93530270fcddedfc671610d975d43059 | sarck1/RoadPython | /chapter004/chapter_0404.py | 594 | 4.34375 | 4 | # 字符串
str = 'Python全栈工程师'
# 索引
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
# 连接
print(str + "魔鬼训练营")
# 转义
print("换行\r\n")
print("Tab制表符\t")
# 成员运算符
if 'P' in str:
print("P is in ", str)
# 格式化符
print("PI = %.2f" % 3.1415926)
| false |
60a60eb4b62884547b8ccf65709a8a263cabb7f7 | sarck1/RoadPython | /chapter010/chapter_01004.py | 1,527 | 4.28125 | 4 | # 类的继承
class BaseClass:
"""基类"""
# 成员变量
def __init__(self, age, name, job): # 特殊函数:双下划线开始+双下划线结束,系统定义的特殊函数,不能在类外部访问
self.age = age # 公有成员: 对所有人公开,可以在类的外部直接访问
self._name = name # 保护成员:不能够通过 "from module import *" 的方式导入
self.__job = job # 私有成员:双下划线开始,无双下划线结束;类的外部不能直接访问,需要调用类的公开成员方法访问
print("BaseClass init")
# 成员函数
def get_age(self):
print(self.age)
return self.age
def set_age(self, age):
self.age = age
print(age)
# 保护成员函数
def _get_name(self):
return self._name
# 私有成员函数
def __get_job(self):
return self.__job
# 派生类
class DriverdClass(BaseClass):
def __init__(self, age, name, job, cardno):
BaseClass.__init__(self, age, name, job)
self.cardno = cardno
print("DriverdClass init")
def get_age(self):
print("DriverdClass get_age")
def main():
# 有参数的对象声明
mycls = DriverdClass(20, "张子良", "Python全栈工程师", "SVIP_0001")
mycls.get_age() # 增加重载的情况
print(mycls._name)
mycls._get_name() # 访问保护成员函数
# 执行主函数
if __name__ == '__main__':
main() | false |
64d9452fdfef119059012760b7e930c5ba154be3 | Bibin22/pythonpgms | /Pattern programs/28. S star.py | 279 | 4.125 | 4 | for raw in range(7):
for col in range(7):
if (col == 0 and(raw>0 and raw < 3)) or (col ==6 and(raw > 3 and raw < 6)) or ((raw == 0 or raw == 3 or raw == 6) and col > 0 and col < 6):
print("*", end="")
else:
print(end=" ")
print("") | false |
d4152592f91b7193450dd6136cc34e678c6a95fa | MOHAMMAD-FATHA/Python_Programs | /Data Structures/Dictionary/IterateDic.py | 333 | 4.125 | 4 | """
* @Author: Mohammad Fatha
* @Date: 2021-09-24 15:50
* @Last Modified by: Mohammad Fatha
* @Last Modified time: 2021-09-15 01:52
* @Title: :Python program to iterate over the dictionary using loops
"""
d = {'Name': "Fatha", 'Age': 24, 'Designation': "Data Engineer"}
for dict_key, dict_value in d.items():
print(dict_key,'->',dict_value) | false |
0d8f8fc8b53933cea270c857ee3b2a0cc9caf47f | MOHAMMAD-FATHA/Python_Programs | /Data Structures/Lists/CheckIdenticalList.py | 887 | 4.25 | 4 | """
* @Author: Mohammad Fatha
* @Date: 2021-09-27 00:21
* @Last Modified by: Mohammad Fatha
* @Last Modified time: 2021-09-27 00:22
* @Title: :Python program to append a list to the second list.
"""
import collections
l1 = [2, 1, 4, 3, 5]
l2 = [1, 2, 4, 3, 5]
# printing lists
print ("The first list is : " + str(l1))
print ("The second list is : " + str(l2))
# sorting both the lists
l1.sort()
l2.sort()
# using == to check if
# lists are equal
if l1 == l2:
print ("The lists are identical")
else :
print ("The lists are not identical")
l3 = [6, 1, 4, 3, 5]
l4 = [1, 2, 4, 3, 5]
# printing lists
print ("The first list is : " + str(l3))
print ("The second list is : " + str(l4))
# using collections.Counter() to check if
# lists are equal
if collections.Counter(l3) == collections.Counter(l4):
print ("The lists are identical")
else :
print ("The lists are not identical") | true |
0099db536d4d83c567c957e403d226657dfa16cb | VikingOfScrum/Inclass-unittest-pytest-and-coverage | /joseph_hanson_hw1.py | 1,499 | 4.4375 | 4 | '''
Simple program to check if inputted year is a leap year or not.
Greet user
Ask user for input
if input is not valid ask again for input
check if input is valid int or exit
if input is not valid and input is exit, exit program
if input is valid check if given year is leap
print output
Joseph Hanson
'''
def print_if_leap(input_year):
'''
Checks if input is a leap year.
leap years are years divisable by 4 and or 400
non leap years all years not divisable by 4 and or 400
'''
input_year = int(input_year)
if input_year % 100 == 0 and input_year % 400 != 0:
print(input_year, "is not a leap year.")
return False
elif input_year % 4 == 0 or input_year % 400 == 0:
print(input_year,"is a leap year.")
return True
else:
print(input_year, "is not a leap year.")
return False
def main():
'''
Main driver function for the assignment.
greets users with what the program does.
uses a for loop to repeat while play is True.
asks user for input then sends input to check function.
if check function returns true sends it to print leap year function.
if user types 'exit' play will become false and exit the program.
'''
print("Hello, This program is designed to check if the input year is a leap year.")
play = True
exit_program = "exit"
input_year = input("Please enter a year or type 'exit' to quit: ")
print_if_leap(input_year)
if __name__=='__main__':
main() | true |
31fe0454b387999e6629dd49af914c34b591e1e1 | liawbeile/learningpython | /filespractice.py | 2,169 | 4.25 | 4 | # Prac 1
# Read all lines in a text file
with open('random.txt','r') as f:
while True:
lines = f.readline()
if lines:
print(lines)
else:
break
# with opening of the random.txt file, to read, as f
# while the file is open
# set variable 'lines' = read one line in the text file
# if lines i.e. if able to read one line in the text file, then print the line
# else, break
# Prac 2
# Read first n lines of a file
#Using readlines()
number = int(input('Number:'))
i=0
with open('random.txt','r') as f:
lines = f.readlines()
for line in lines:
i+=1
if i<=number:
print(line)
#should break out of the loop after there is no need to print
#else this solution will iterate through the entire file even if it does not have to print
else:
break
# find n from user
# set i=0
# opening of the text file & to read, set as f
# set 'lines' variable to read all lines in the file
# for every line in all the lines
# i + 1 every time it goes to a new line
# if lines are being read and i<= user input n, print the line
#Alternative solution using readline():
number = int(input('Number:'))
i=0
with open('random.txt','r') as f:
while True:
lines = f.readline()
if lines and i<number:
i += 1
print(lines)
else:
break
# find n from user
# set i=0
# opening of the text file & to read, set as f
#while text file is open
# set 'lines' variable to read line by line in the file
# i + 1 every time it goes to a new line
# if i < user input n, print the line
# Prac 3
# Append text to a file and display the text
sentence = "This is a new sentence"
with open('random.txt','a') as f:
f.write("\n")
f.write(sentence)
#when file is open and we want to append
#append "next line"
#append the new sentence
# Prac 4
# Read all lines
with open('random.txt','r') as f:
lines = f.readlines()
for line in lines:
print(line)
# opening of the text file & to read, set as f
# set 'lines' variable to all lines in the file
# for every line in lines
# print the line | true |
fbbc5c606e435a2c047ef31d12b7ff007e5bd601 | RawalD/Python-Small-Apps | /2/tip_calculator.py | 382 | 4.1875 | 4 | print('Welcome to the tip calculator')
bill_total = float(input('What was the total bill ?\n'))
people = int(input('How many people to split the bill by ?\n'))
tip_percentage = int(
input('What percentage tip would you like to give ?\n10, 12, 15 ?\n'))
tip_calc = bill_total / people + (bill_total * (tip_percentage / 100 / people))
print(f'Each person should pay: {tip_calc}')
| false |
275ea62dc6b59df0089c9993fce04838809930c2 | RawalD/Python-Small-Apps | /29/app.py | 206 | 4.125 | 4 | # Acronym maker
user_text = input('Please enter a string to convert:\n')
user_text = user_text.split()
acronym = ''
for letter in user_text:
acronym = acronym + str(letter[0]).upper()
print(acronym)
| true |
d50a31d6ddd9053fb90fd1e10e5f497030959a67 | MDCGP105-1718/portfolio-alex-turnbull | /ex7.py | 624 | 4.21875 | 4 | annual_salary = float(input("Enter your annual salary: "))
portion_save = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
portion_deposit = 0.2
current_savings = 0.0
r = 0.04
deposit = total_cost*portion_deposit
monthly_salary = annual_salary/12
current_savings += portion_save*monthly_salary
totalMonths = 0
reachedDeposit = False
while (not reachedDeposit):
totalMonths += 1
current_savings += current_savings*r
if (current_savings > deposit):
reachedDeposit = True
print("\nNumber of months:",totalMonths)
| true |
3d065a3a7a2a4cd5d136fd77e0507ec4ad116050 | bradagy/rot13 | /rot13/rot13.py | 619 | 4.125 | 4 | #!/usr/bin/env python3
import string
def encrypt(text, n):
in_tab = string.ascii_lowercase
out_tab = in_tab[n % 26:] + in_tab[:n % 26]
trans_tab = str.maketrans(in_tab, out_tab)
return text.translate(trans_tab)
def rot13():
while True:
user_input = input('Please enter the text here: ')
if not user_input.isalpha():
print('The input you entered was not correct. Numbers are also '
'not accepted. Please try again.')
continue
else:
print(f"The encryption is {encrypt(user_input, 13)}.")
break
rot13()
| true |
5d31f9b13a29f863cc7f53f98e340180dfdaed5f | hooke-naoto/Python_Training | /_13_Class_Composition.py | 563 | 4.21875 | 4 | # 2 different classes, but one has another's object.
class Dog:
def __init__(self, name, breed, owner):
self.name = name
self.breed = breed
self.owner = owner
class Person: # The object "Person" will be a variable in Dog().
def __init__(self, name):
self.name = name
mick = Person("Mick Jagger")
stan = Dog("Stanley", "Bulldog", mick) # "mick" is an object, but also a variable as "owner" in Dog().
print(stan.owner.name) # "stan.owner" is also an object in Person(), so you can describe further period and variable name.
| true |
e368ce3117ddf56d533dcade1aed3a93cf05340b | MacroBet/python_examples | /types.py | 1,111 | 4.1875 | 4 | # INSTANCE
x = 200
print(isinstance(x, int))
# BITWHISE OPERATIONS
"""
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
"""
# TYPES
x = "Hello World" #str
x = 20 #int
x = 20.5 #float
x = 35e3
y = 12E4
z = -87.7e100
x = 1j+1 #complex
print("complex")
print(x)
x = ["apple", "banana", "cherry"] #list
x = ("apple", "banana", "cherry") #tuple
x = range(6) #range
print("range")
print(x)
x = {"name" : "John", "age" : 36} #dict
print("dict")
print(x)
x = {"apple", "banana", "cherry"} #set
x = frozenset({"apple", "banana", "cherry"}) #frozenset
print("frozenset")
print(x)
x = True #bool
x = b"Hello" #bytes
print("bytes")
print(x)
x = bytearray(5) #bytearray
print("bytearray")
print(x)
x = memoryview(bytes(5)) #memoryview
print("memoryview")
print(x)
| true |
5d32beaae91cb6e690561f6976d81ec4b27187cb | mylgood/myl_good_demo | /code/chapter04/15_lambda表达式.py | 1,398 | 4.1875 | 4 | # 用于计算两个数的和
'''
def sum(x,y):
""" 用于计算两个数的和"""
return x + y
sum2 = lambda x,y:x+y
print(sum(1,2))
print(sum2(1,9))
print(sum2)
# 通过lambda表达式简化代码
# lambda 可以所谓一个函数的参数
def go_home(callback):
print("开始执行")
callback();
print("完成执行")
# fn = lambda : print("lmbda函数")
go_home(lambda : print("lmbda函数"))
'''
'''
def max(x,y):
"返回x,y中的最大值"
"""
if x >= y:
return x
else:
return y
"""
# 三元运算符
return x if x >= y else y
# lambda 表达式用于逻辑比较简单,
max2 = lambda x,y:x if x >= y else y
print(max(10,4))
print(max2(99,78))
'''
def max(x,y,z):
"""返回x,y,z中的最大声"""
"""
return x if x>=y and x >= z else y if y>=x and y>=z else z
"""
print(123)
print(456)
if x>=y and x >= z:
return x
elif y>=x and y>=z:
return y
else:
return z
# 在不够清晰的时候,不建议使用lambda表达式
max2 = lambda x,y,z:x if x>=y and x >= z else y if y>=x and y>=z else z
print(max(1,13,5))
print(max2(1,13,5))
print("*"*50)
# 在表达式中执行多个语句 需要使用逻辑运算符or 或者 and
max3 = lambda x,y,z:print(123) or print(456) or (x if x>=y and x >= z else y if y>=x and y>=z else z)
print(max3(1,13,5))
| false |
d5e1eb64123c31df1e349645eb20b192a6cae07c | snidarian/python-cli-math-tools | /sqr.py | 648 | 4.21875 | 4 | #! /usr/local/bin/python3.9
# change above shebang line to reflect absolute path to preferred python interpreter
# takes single integer/float value and displays its square to stdout
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=float, help="display square of given number")
parser.add_argument("-v", "--verbose", type=int, help="increase output verbosity", choices=[0, 1, 2])
args = parser.parse_args()
answer = args.square**2
if args.verbose == 2:
print(f"The square of {args.square} is {answer}")
elif args.verbose == 1:
print(f"{args.square}^2 == {answer}")
else:
print(answer)
| true |
460f125c45a544cf9bc023e45a420f8ab597babe | S-Agnihotri/LetsUpgrade | /Day-2/Assignment-2_Q-2.py | 372 | 4.25 | 4 | # Check whether a string is a pangram.
alphabet = "abcdefghijklmnopqrstuvwxyz"
sentence = input("Please enter your sentence below:\n")
pangram = True
for char in alphabet:
if char not in sentence.lower():
pangram = False
if pangram:
print("Entered sentence is a pangram.")
else:
print("Entered sentence is not a pangram.")
| true |
3edd6477397f788476e32919acf2bfda757aa83e | ZarmeenLakhani/Python-Documentation | /Sets.py | 941 | 4.375 | 4 | #set uses curly brackets, braces
#you CAN NOT have duplicates in the set .
# unordered. You can't iterate. there is no 0th or 1st element.bro, no order
#we can cast a list to sets which means it will get rid of the repeated elements
#and convert it riht back in a list again.
s={"blueberry", "rasberry"}
print(s)
#it spits out result in random order. sets are like a bag of thing
s.add('stawberry')
s.add('blueberry')
s.add('4')
print(s)
#list to sets
l=[1,1,1,1,1,1,4,4,4,4,4,2,2,2,2,2,2,,9,,9,9,9,9,9,3,3,3,3,3]
le=set(l)
li=list(le)
print(li)
#function of Venn Diagram
library_1={"Harry Potter", "Monster calls", "Romeo and Juliet"}
library_2={"Monster calls", "Peaky Binder", "Die Young"}
Book_town=library_1.union(library_2)
print(Book_town)
similar_books=library_1.intersection(library_2)
diff_book=library_1.difference(library_2)
#this function would return elements from list1 that are not in list 2.
print(similar_books)
print(diff_book)
| true |
8d2e61131e058acc93efbcf5c9f64ac4e91773f3 | KunyiLiu/algorithm_problems | /kangli/geeksforgeeks/who_has_majority.py | 2,669 | 4.28125 | 4 | '''
We hope you are familiar with using counter variables. Counting allows us to find how may times a certain element appears in an array or list.
You are given an array arr of size n. You are also given two elements x and y. Now, you need to tell which element (x or y) appears most in the array. In other words, print the element, x or y, that has highest frequency in the array. If both elements have the same frequency, then just print the smaller element.
Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains 3 lines of input. The first line contains size of array denoted by n. The second line contains the elements of the array separated by spaces. The third line contains two integers x and y separated by a space.
Output Format:
For each testcase, in a newline, print the element with highest occurrence in the array. If occurrences are same, then print the smaller element.
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function majorityWins() that takes array, n, x, y as parameters.
Constraints:
1 <= T <= 100
1 <= n <= 103
0 <= arri , x , y <= 108
Examples:
Input:
2
11
1 1 2 2 3 3 4 4 4 4 5
4 5
8
1 2 3 4 5 6 7 8
1 7
Output:
4
1
Explanation:
Testcase 1: n=11; elements = {1,1,2,2,3,3,4,4,4,4,5}; x=4; y=5
x frequency in arr is = 4 times
y frequency in arr is = 1 times
x has higher frequency, so we print 4
Testcase 2: n=8; elements = {1,2,3,4,5,6,7,8}; x=1; y=7
x frequency in arr is 1 times
y frequency in arr is 1 times
both have same frequency, so we look for the smaller element.
x=1 is smaller than y=7, so print 1
** For More Input/Output Examples Use 'Expected Output' option **
Author: Soul_xhacker
'''
def main():
T = int(input())
while (T > 0):
n = int(input())
arr = [int(x) for x in input().strip().split()]
x, y = map(int, input().strip().split())
majorityWins(arr, n, x, y)
T -= 1
if __name__ == "__main__":
main()
''' Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above. '''
# User function Template for python3
# Initial Template for Python 3
# Complete this function
def majorityWins(arr, n, x, y):
x_count, y_count = 0, 0
for elt in arr:
if elt == x:
x_count += 1
elif elt == y:
y_count += 1
if x_count == y_count:
print(x) if x < y else print(y)
return
print(x) if x_count > y_count else print(y)
| true |
7ff16ae3c256fb75948f95dd42dd55db5d5191e9 | datadavis2/hackerrank | /python/if_else.py | 714 | 4.1875 | 4 | '''
Task
Given an integer, , perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive range of 2 to 5, print Not Weird
If is even and in the inclusive range of 6 to 20, print Weird
If is even and greater than 20, print Not Weird
Input Format
A single line containing a positive integer, .
Constraints
1 <= n <= 100
Output Format
Print Weird if the number is weird; otherwise, print Not Weird.
https://www.hackerrank.com/challenges/py-if-else/problem
'''
n = int(input())
def isOdd(x):
if x % 2 == 0:
return False
else:
return True
if isOdd(n):
print("Weird")
elif n >= 6 and n <= 20:
print("Weird")
else:
print("Not Weird")
| true |
d42fe2aecd326635793014a754dd27d928f5e1a5 | joannamiltner/Python-Functions | /Functions Basic II.py | 2,106 | 4.28125 | 4 | # # 1. Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element). Example: countdown(5) should return [5,4,3,2,1,0]
# def countdown(num):
# newOutput=[]
# while num >=0:
# newOutput.append(num)
# num-=1
# return newOutput
# print(countdown(5))
# # 2. Create a function that will recieve a list with two numbers. Print the first value and return the second. Example: print_and_return ([1,2]) should print 1 and return 2
# def print_and_return(arr):
# print (arr[0])
# return arr[1]
# print_and_return([1,2])
# # 3. Create a function that accepts a list and returns the sum of the first list plus the list's length. Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1+length: 5)
# def first_plus_length(arr):
# a=arr[0]
# b=len(arr)
# return a+b
# print(first_plus_length([1,2,3,4,5]))
# # 4. Write a function that accepts a list and createsa new list containting only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False. Example: values_greater_than_second ([5,2,3,2,1,4]) should print 3 and return [5,3,4]. and _seconds[3] should return False
# def values_greater_than_second(arr):
# for i in range(len(arr)):
# if arr[i] >= i[2]:
# arr.pop(i)
# arr[i]+=1
# print(len(arr))
# if len(arr)<2:
# return False
# values_greater_than_second([5,2,3,2,1,4])
# COME BACK TO DEEES
# # 5. Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value. Example: length_and_value(6,2) should return [2,2,2,2,2,2]
# def length_and_value(set):
# size= set[1]
# repeat = set[0]
# print(f"{size},"*repeat)
# length_and_value((6,2))
| true |
a3aa50e0d9a9a83c9449292caf88414a30c7a464 | dkljajo/Python-for-everybody---Coursera | /2. Data Structures/Assignment_07_01/Assignment_07_01.py | 515 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 24 20:39:16 2019
@author: dk
Write a program that prompts for a file name, then opens that file and reads
through the file, and print the contents of the file in upper case.
Use the file words.txt to produce the output below.
You can download the sample data at http://www.py4e.com/code3/words.txt
"""
# Use words.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
for lx in fh:
ly= lx.rstrip()
print(ly.upper())
| true |
af90d4610f7affeb5c473b5e3e9a294490b41560 | dileeppandey/python-problem-solving | /misc/battleship.py | 2,343 | 4.28125 | 4 | """
Battleship is a game in which one player (Player One) places ships, and the other player (Player Two) guesses their
location (this is a simplified version of children's game)
Game Details:
The game is played on a 6x6 grid. Squares are referenced by a letter and number like the following:
| 1 2 3 4 5 6
--+------------
A |
B |
C |
D |
E |
F |
B3 Refers tho 3rd cell on the second row
Sample Input:
[A1, A3, D5, F5], [A2, A3, A4, F4, A1, D5, E5, F5]
Sample Output:
Player One entered 2 ships.
"""
class Cell:
def __init__(self, row, col, val):
self.row = row
self.col = col
self.val = val
def __str__(self) -> str:
return f'{self.row}{self.col} = {self.val}'
class BattleshipBoard():
"""
"""
def __init__(self, rows, cols) -> None:
self._board = [[Cell(row, col, '.') for col in cols] for row in rows]
self._rows = {k:v-1 for v, k in enumerate(rows)}
self._cols = cols
def __getitem__(self, position):
if type(position) == str:
r,c = position[0], int(position[1])
return self._board[self._rows[r]][c-1]
elif type(position) == tuple:
return self._board[position[0]][position[1]]
def __setitem__(self, position, new_val):
if type(position) == tuple:
self._board[position[0]][position[1]].val = new_val
else:
r, c = position[0], int(position[1])
self._board[self._rows[r]][c-1] = new_val
def __str__(self) -> str:
return '\n'.join([''.join([cell.val for cell in row]) for row in self._board])
def is_valid_cell(self, position):
"""Check if a position of a board is valid input
Args:
position: str, A1 - A6 ...
Returns:
bool
"""
return len(position) == 2 and position[0] in self._rows and int(position) in self._cols
class Battleship:
def __init__(self, board) -> None:
self.board = board
def is_valid_move(self, position):
return self.board.is_valid_cell(position)
def play(self, player_one_ships, player_two_guesses):
# sanitize inputs
pass
bs = BattleshipBoard(['A', 'B', 'C', 'D', 'E', 'F'], range(1, 7))
print(bs)
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
| true |
7a9167147d6e513db93b899d470a2f533fd1679d | flaviokosta/python_basico | /aula5-exercicio.py | 807 | 4.25 | 4 | '''
EXERCICIO
Faça um programa que leia a quantidade de pessoas que serão convidadas
para uma festa.
Após isso, o programa irá perguntar o nome de todas as pessoas e colocar
numa lista de convidados.
Após isso, irá imprimir todos os nomes da lista
'''
print('/...............::::...............\\')
print('| Programinha de Festinhas 1.0 |')
print('\...............::::.............../\n')
quantidade = int(input('Quantidade de convidados: '))
convidado = 1
lista_convidados = []
while convidado <= quantidade:
lista_convidados.append(input('Nome do convidado # ' + str(convidado) + ': '))
convidado += 1
print('\n-- LISTA DE CONVIDADOS --')
print('Quantidade de convidados:', quantidade)
print('\n')
for i in range(quantidade):
print('Convidado', (i+1), '-', lista_convidados[i])
| false |
2af5edef57db85f7e51afe5cbf318d8096c541bf | meeere/python-coursera-collection | /04_Score-Grade.py | 911 | 4.40625 | 4 | # Write a program to prompt for a score between 0.0 and 1.0.
# If the score is out of range, print an error.
# If the score is between 0.0 and 1.0, print a grade using the following table:
# Score Grade
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# If the user enters a value out of range, print a suitable error message and exit.
# For the test, enter a score of 0.85.
try:
score = raw_input("Enter Score: ")
S = float(score)
except:
print "Please enter a numeric value between 0.0 and 1.0."
quit()
if S >= 0.0 and S <= 1.0:
if S >= 0.9:
print "Your grade is A."
elif S >= 0.8 and S <= 0.9:
print "Your grade is B"
elif S >= 0.7 and S <= 0.8:
print "Your grade is C"
elif S >= 0.6 and S <= 0.7:
print "Your grade is D"
else :
print "Your grade is F"
else :
print "Please enter a value between 0.0 and 1.0."
quit()
| true |
ccc1a8d9f1712689a047e6d7b47d1d18aea7be32 | j-morris95/python-data-structure-exercise | /07_multiple_letter_count/multiple_letter_count.py | 687 | 4.1875 | 4 | def multiple_letter_count(phrase):
"""Return dict of {ltr: frequency} from phrase.
>>> multiple_letter_count('yay')
{'y': 2, 'a': 1}
>>> multiple_letter_count('Yay')
{'Y': 1, 'a': 1, 'y': 1}
"""
letter_dict = {}
for ltr in phrase:
letter_dict[ltr] = letter_dict.get(ltr, 0) + 1
return letter_dict
# I solved using this line below which I think is a better solution, but
# test 1 fails because the set reorders 'yay' to {'a', 'y'}
# however the returned dictionary still accurately counts the
# number of occurrences of each letter in the phrase
###
# return {ltr: phrase.count(ltr) for ltr in set(phrase)}
| true |
f1c2116b83953950a4ce4f0015e7c8d6f3ff5362 | rkosakov/COS340 | /Lecture 5/summation.py | 204 | 4.15625 | 4 | lower = int(input('Enter the lower bound: '))
upper = int(input('Enter the upper bound: '))
theSum = 0
for number in range(lower, upper + 1):
theSum = theSum + number
print(f'The sum is {theSum}')
| true |
23f48a2e180507959b7abfd7b1a445eee005004a | rkosakov/COS340 | /Lecture 5/Tutorial Session/Scores.py | 732 | 4.15625 | 4 | numberStudents = eval(input('Enter the number of students: '))
highestScore = 0
secondHighestScore = 0
middleScore = 0
highestName = ''
middleName = ''
secondName = ''
for i in range(1, numberStudents + 1):
student = input('Enter a student name: ')
score = eval(input('Enter a score for the student: '))
if score > highestScore:
middleScore = highestScore
highestScore = score
secondHighestScore = middleScore
middleName = highestName
highestName = student
secondName = middleName
print(f'Student {highestName} has the highest score of {highestScore}')
print(f'Student {secondHighestScore} has the second highest score of {secondHighestScore}')
| true |
241aa84687798c27c92f32af198159ed9b38cac8 | bolducp/My-Think-Python-Solutions | /chpz11/11.0.01.py | 798 | 4.1875 | 4 | """Write a function that reads the words in words.txt and stores
them as keys in a dictionary. It doesn’t matter what the values are.
Then you can use the in operator as a fast way to check whether a
string is in the dictionary.
If you did Exercise 11, you can compare the speed of this implementation
with the list in operator and the bisection search."""
def make_word_list(file):
word_list = open(file)
list = []
for line in word_list:
word = line.strip()
list += [word]
return list
wordlist = make_word_list("words.txt")
def make_dictionary(list):
word_dict = dict()
for word in list:
word_dict[word] = ''
return word_dict
dictlist = make_dictionary(wordlist)
def check_for_string(word, dictionary):
return word in dictionary
| true |
2b19ff326b52a6b2bc7968ce44682f850cbe9bbb | bolducp/My-Think-Python-Solutions | /chpz10/10.15.06.py | 742 | 4.28125 | 4 | """ Write a function called is_sorted that takes a list as a
parameter and returns True if the list is sorted in ascending
order and False otherwise. You can assume (as a precondition)
that the elements of the list can be compared with the relational
operators <, >, etc.
For example, is_sorted([1,2,2]) should return True and is_sorted(['b','a'])
should return False."""
def is_sorted(a_list):
if a_list == sorted(a_list):
return True
return False
#OR (simplified)
def is_sorted2(a_list):
return a_list == sorted(a_list)
#OR (not using the built-in sorted function)
def is_sorted3(a_list):
for num in range(len(a_list) - 1):
if a_list[num] > a_list[num + 1]:
return False
return True
| true |
75b9dff2dbae4084f5dc89a58542da5365953b6d | bolducp/My-Think-Python-Solutions | /chpz12/12.04.01.py | 365 | 4.3125 | 4 | """Many of the built-in functions use variable-length argument
tuples. For example, max and min can take any number of arguments:
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
Write a function called sumall that takes any number of arguments
and returns their sum."""
def sumall(*args):
return sum(args) | true |
48c19afbb9121927fc0ae1bd0ed222ea08c0349a | bolducp/My-Think-Python-Solutions | /chpz13/13.12.09.py | 1,910 | 4.40625 | 4 | """The “rank” of a word is its position in a list of words sorted by
frequency: the most common word has rank 1, the second most common has
rank 2, etc.
Zipf’s law describes a relationship between the ranks and frequencies
of words in natural languages (http://en.wikipedia.org/wiki/Zipf's_law).
Specifically, it predicts that the frequency, f, of the word with rank r is:
f = c r−s
where s and c are parameters that depend on the language and the text.
If you take the logarithm of both sides of this equation, you get:
logf = logc − s logr
So if you plot log f versus log r, you should get a straight line with
slope −s and intercept log c.
Write a program that reads a text from a file, counts word frequencies,
and prints one line for each word, in descending order of frequency,
with log f and log r. """
import math
def make_word_histogram(a_file):
text = []
fin = open(a_file)
for line in fin:
word = line.strip().split()
text += word
histo = {}
for word in text:
histo[word] = histo.get(word, 0) + 1
return histo
def sort_by_first_item(item):
return item[0]
def make_sorted_tuples_list(a_histo):
tuples = a_histo.items()
reversed_tuples =[(v, k) for (k, v) in tuples]
reversed_tuples = sorted(reversed_tuples, key=sort_by_first_item, reverse=True)
return reversed_tuples
def print_freq_and_rank_logs(list_of_tuples):
new_list = []
for r, (freq, word) in enumerate(list_of_tuples, 1):
new_list += [(freq, word, r)]
list_with_logs = [(w, math.log(f), math.log(r)) for (f, w, r) in new_list]
for item in list_with_logs:
print item[0] + "/ log f: " + str(item[1]) + " / log r: " + str(item[2])
def main(a_file):
text = make_word_histogram(a_file)
sorted_tuples = make_sorted_tuples_list(text)
results = print_freq_and_rank_logs(sorted_tuples)
return results
| true |
1351d557ae8b8009c5e02ecc9a635ef1a53fa14c | bolducp/My-Think-Python-Solutions | /chpz15/15.09.04.py | 2,490 | 4.84375 | 5 | """If you add this line to the program, the result should resemble the national flag of
Bangladesh (see http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags).
Write a function called draw_rectangle that takes a Canvas and a Rectangle as arguments
and draws a representation of the Rectangle on the Canvas.
Add an attribute named color to your Rectangle objects and modify draw_rectangle so that
it uses the color attribute as the fill color.
Write a function called draw_point that takes a Canvas and a Point as arguments and draws
a representation of the Point on the Canvas.
Define a new class called Circle with appropriate attributes and instantiate a few Circle
objects. Write a function called draw_circle that draws circles on the canvas.
Write a program that draws the national flag of the Czech Republic. Hint: you can draw a
polygon like this:
points = [[-150,-100], [150, 100], [150, -100]]
canvas.polygon(points, fill='blue')"""
from swampy.TurtleWorld import *
class Point(object):
"represents a point in 2-D space"
p = Point()
p.x = 60
p.y = 15
class Rectangle(object):
"""Represents a rectangle."""
box = Rectangle()
box.color = 'blue'
box.bbox = [[-100, -60],[100, 60]]
class Canvas(object):
"""Represents a canvas.
attributes: width, height, background color"""
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500
class Circle(object):
"""Represents a circle.
attributes: center point, radius"""
c = Circle()
c.radius = 50
c.center = Point()
c.center.x = 20
c.center.y = 20
def draw_rectangle(canvas, rectangle):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(rectangle.bbox, fill=rectangle.color)
def draw_point(canvas, point):
bbox = [[point.x, point.y], [point.x, point.y]]
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(bbox, fill="black")
def draw_circle(canvas, circle):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.circle([circle.center.x, circle.center.y], circle.radius)
def draw_czech_republic_flag(canvas):
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle([[-100, 60], [100, 60]], outline=None, fill='white')
drawn_canvas.rectangle([[-100, -60], [100, 0]], outline=None, fill='red2')
points = [[-100,-60], [-100, 60], [0, 0]]
drawn_canvas.polygon(points, fill='blue3')
world = World()
draw_czech_republic_flag(a_canvas)
world.mainloop()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.