blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9a890f9b78d267a5736ee72bcae20c51ac68cbb2 | FigX7/digital_defense | /application/core/helpers.py | 542 | 4.375 | 4 | # https://www.geeksforgeeks.org/python-make-a-list-of-intervals-with-sequential-numbers/
# Python3 program to Convert list of
# sequential number into intervals
import itertools
def intervals_extract(iterable):
iterable = sorted(set(iterable))
for key, group in itertools.groupby(enumerate(iterable),
lambda t: t[1] - t[0]):
group = list(group)
yield [group[0][1], group[-1][1]]
def divide_chunks(list_obj, n):
for i in range(0, len(list_obj), n):
yield list_obj[i:i + n] | true |
69fd0de981980ceb937c1de1ff1f5d15e9e9412f | lauralevy111/python_for_programmers | /src/notes/sets.py | 803 | 4.125 | 4 | #Sets
#list of singers w a duplicate item
#faveSingers = ["Dolly Parton", "Whitney Houston", "Mariah Carey", "Celine Dion","Lady Gaga","Whitney Houston"]
#Whitney Houston is two elements, theres a dupe in this list
#print(faveSingers)
#^tolerates dupe, prints: ['Dolly Parton', 'Whitney Houston', 'Mariah Carey', 'Celine Dion', 'Lady Gaga', 'Whitney Houston']
#set of singers w a duplicate item
faveSingers = set(["Dolly Parton", "Whitney Houston", "Mariah Carey", "Celine Dion","Lady Gaga","Whitney Houston"])
#removed dupe.
print(faveSingers) #prints:{'Whitney Houston', 'Dolly Parton', 'Mariah Carey', 'Celine Dion', 'Lady Gaga'}
#can i print an item by index?no :/
#print(faveSingers[2])#returns: TypeError: 'set' object is not subscriptable
#how do i append an item to the end?:
faveSingers.add("Robyn")
faveSingers = ["Dolly Parton", "Whitney Houston", "Mariah Carey", "Celine Dion","Lady Gaga","Whitney Houston"]
setFaveSingers = set(faveSingers)
print(setFaveSingers)
| false |
89a2a8bb4638493f1af993a622a97962cffbef25 | uccser/codewof | /codewof/programming/content/en/prime-numbers/solution.py | 378 | 4.25 | 4 | number = int(input("Enter a positive integer: "))
if number < 2:
print('No primes.')
else:
print(2)
for possible_prime in range(3, number + 1):
prime = True
for divisor in range(2, possible_prime):
if (possible_prime % divisor) == 0:
prime = False
break
if prime:
print(possible_prime)
| true |
9f245e8df74b53459c8a0c35cd136707132a6dcd | urvish6119/Python-Algorithms-problem | /Binary Search.py | 576 | 4.125 | 4 | # Binary Search is only useful on ordered list.
def binary_search(list1, ele):
if len(list1) == 0:
return False
else:
mid = len(list1) / 2
if list1[mid] == ele:
return True
else:
if ele < list1[mid]:
return binary_search(list1[:mid], ele)
else:
return binary_search(list1[mid + 1:], ele)
print('enter array elements here with space')
list_i = [int(a) for a in input().split()]
search = int(input('please enter number you want to find.'))
binary_search(list_i, search)
| true |
2f2878c4e9129f76ab87f5eeb05d5632699a3618 | LeakeyMokaya/Leakey_BootCamp_Day_4 | /Missing_Number/missing_number.py | 885 | 4.125 | 4 | def find_missing(list1, list2):
if isinstance(list1, list) and isinstance(list2, list):
list1_length = len(list1)
list2_length = len(list2)
# return 0 if the lists are empty
if list1_length == 0 and list2_length == 0:
return 0
else:
# Convert lists to set data structure because it can get difference between sets
set_list1 = set(list1)
set_list2 = set(list2)
if list1_length > list2_length:
return list(set_list1 - set_list2).pop()
elif list2_length > list1_length:
return list(set_list2 - set_list1).pop()
else:
if list(set_list2 - set_list1) == []:
return 0
elif list(set_list2 | set_list1) == list2 and list(set_list2| set_list1) == list1:
return 0 | true |
c8cb04f08fda42c79b360e65dc7ba56fd8f0f9f8 | pyaephyokyaw15/PythonFreeCourse | /chapter5/tuple_upack2.py | 470 | 4.125 | 4 | my_tuple = "Aung Aung",23,"Description"
name,age,_ = my_tuple #name = my_tuple[0], age = my_tuple[1]
print("Name ",name, " Age ",age)
name = name.upper
print("My Tuple ",my_tuple)
my_lst = [1,2,2,3]
another_tuple = (my_lst,1)
another_lst,_= another_tuple
another_lst[0] = 100
print("Another list ",another_lst)
print("My list ",my_lst)
print("Another list is my_lst",another_lst is my_lst)
def process(*argv):
print("Argv ",argv, type(argv))
process(1,2,"Hello") | false |
3ca889f0fbe4b6a823a7cb47d0f4dbfdb4dfccaa | pyaephyokyaw15/PythonFreeCourse | /chapter5/tuple_operator.py | 906 | 4.25 | 4 | one_to_ten = range(0,5)
my_tuple = tuple(one_to_ten)
print("Tuple constructor from range ",my_tuple)
another_tuple = tuple(range(20,25))
print("Another tuple ",another_tuple)
third_tuple = my_tuple + another_tuple
print("Third tuple ",third_tuple)
fruits = ("Orange","Apple","Banaa")
fruits_repeated = fruits * 3
print("Fruit repeated ",fruits_repeated)
print("Fruit repeated len ",len(fruits_repeated))
print("Fruit repeated count(Apple) ",fruits_repeated.count("Apple"))
print("Fruit repeated index(Apple) ",fruits_repeated.index("Apple"))
#print("Fruit repeated index(Apple) ",fruits_repeated.index("Apple1"))
print("String index ","Hello".find("Hello1"))
another_tuple = (1,2,3,4,5)
sorted_tuple = sorted(another_tuple)
print("Sorted ",sorted_tuple)
print("Min ",min(another_tuple))
print("Max ",max(another_tuple))
string_tuple = "One","Two","Three"
print("Sorted string ",sorted(string_tuple)) | true |
3e1d2cad58d37d35dd69a6249dbf1845069cfa97 | hendry-ref/python-topic | /references/printing_ref.py | 2,319 | 4.28125 | 4 | from string import Template
from helper.printformatter import pt
"""
Ref: https://pyformat.info/ for all string formatting purposes
Topics:
- basic printing
- format printing ( % , f"..", format, template)
- string template
- escape character
"""
@pt
def basic_print():
my_var = "hello world"
print("Hello world")
print(my_var)
print("[1] I'm printing " + my_var)
print("[2] I'm printing ", my_var)
@pt
def print_formatting():
"""
Multiple way of formatting:
- "... %s %d ..." % ("hello", 5)
- f"... {var} ..."
- "... %s %d ...".format(var)
"""
my_var = "hello world"
my_num = 12123816.349
print(f"[3] I'm printing {my_var}, which has length {len(my_var)}")
print("[4] I'm printing %s with %.2f" % (my_var, my_num)) # str % (tuple)
print("$ {:,.2f}".format(my_num)) # print currency with comma as thousandth separator and 2 decimal
def print_template_string():
# method-1 : using .format(...)
str1 = "you're watching '{0}' by {1}, {0} is a great topic.".format("Method-1", "Hendry")
print(str1)
# method-2 : using .format( keyword )
str2 = "the {q} {b} {f}".format(q='quick', b='brown', f='fox')
print(str2)
# method-3 : using template string [keyword-argument]
template = Template("you're watching '${title}' by ${author}, ${title} is a great topic.")
str3 = template.substitute(title='Method-2', author="Leon")
print(str3)
# method-4 : using template string [dictionary-argument]
data = {
'author': 'george',
'title': 'Method-3',
'titlea': 'Method-3' # this will be ignored
}
str4 = template.substitute(data)
print(str4)
# method-5 : using value:width.precision
result = 100 / 777
print("the result of 100/777 is {r:10.3} -- Good stuff!".format(r=result)) # r:width.precision
print(f"the result of 100/777 is {result:10.3f} -- Good stuff!")
@pt
def print_property():
# sep for separating objects passed into print(...). (default = "")
print("This", "is", "\"my\"", "name", sep=" ---")
# end is for end of print. (default = \n)
for i in range(3):
print(i, end=",")
def main():
basic_print()
print_formatting()
print_template_string()
print_property()
if __name__ == '__main__':
main()
| true |
96ed632e616310f72e043fd16d103e1fe0d8eeab | zdravkob98/Fundamentals-with-Python-May-2020 | /Programming Fundamentals Final Exam Retake - 9 August 2019/Username.py | 1,199 | 4.25 | 4 | username = input()
data = input()
while data != 'Sign up':
tolken = data.split()
command = tolken[0]
if command == 'Case':
type = tolken[1]
if type == 'lower':
username = username.lower()
elif type == 'upper':
username = username.upper()
print(username)
elif command == 'Reverse':
start_index = int(tolken[1])
end_index = int(tolken[2])
if 0 <= start_index <= len(username) - 1 and 0 <= end_index <= len(username) - 1:
substring = username[start_index:end_index + 1]
print(substring[::-1])
elif command == 'Cut':
substring = tolken[1]
if substring in username:
username = username.replace(substring, '')
print(username)
else:
print(f"The word {username} doesn't contain {substring}.")
elif command == 'Replace':
char = tolken[1]
username = username.replace(char, '*')
print(username)
elif command == 'Check':
char = tolken[1]
if char in username:
print("Valid")
else:
print(f"Your username must contain {char}.")
data = input() | false |
df8fb9f199ff173e30d1b9da11f5c8c24319955d | VCloser/CodingInterview4Python | /chapter_2/section_3/question_3.py | 1,648 | 4.125 | 4 | # -*- coding:utf-8 -*-
"""
问题:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。
数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。
请找出数组中任意一个重复的数字。
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
"""
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(numbers, duplication):
"""
:param numbers: []
:param duplication: []
:return: bool
"""
for i, val in enumerate(numbers):
if i!=val:
if numbers[numbers[i]]==val:
duplication[0] = val
return True
numbers[i] = numbers[val]
numbers[val] = val
return False
# 输出duplication
def duplicate2(numbers):
"""
:param numbers: []
:return repeatedNums: []
"""
if numbers == None or len(numbers) <= 0:
return False
for i in numbers:
if i < 0 or i > len(numbers) - 1:
return False
repeatedNums = []
for i in range(len(numbers)):
while numbers[i] != i:
if numbers[i] == numbers[numbers[i]]:
repeatedNums.append(numbers[i])
break
else:
index = numbers[i]
numbers[i], numbers[index] = numbers[index], numbers[i]
return repeatedNums
if __name__ == '__main__':
numbers = [2,3,1,0,2,5,3]
duplication = [0]
print(duplicate(numbers,duplication))
print(duplicate2(numbers)) | false |
be759543df287c17d99fd51899e6b4025b2a4a5b | VamsiKrishna04/Hacktoberfest-2021 | /hill-cipher-encryption.py | 2,052 | 4.3125 | 4 | ## cryptography - Hill cipher encryption algorithm implementation
## input - any plaintext and a key(mostly used of size 9)
## Matrix of 3*3 is formed
## Output is a ciphertext generated using hill cipher encryption algorithm
## Characters considered for encryption are A-Z and ".,!" So mod 29 method is used
## eg. Sample inputs - Plaintext - ACT, key - GYBNQKURP
## Output - JTA
plainText = input("Enter the Plain Text: ").upper()
key = input("Enter the key: ").upper()
plainText = "".join(u for u in plainText if u not in ("?", " ", ";", ":", "/", "[", "]"))
x = len(plainText)%3
if(x!=0):
for i in range(3-x):
plainText += 'X'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ.,!'
#generate key matrix from input key string
#As key is a string of length 9, key matrix will be 3x3
keyMatrix = [[0] * 3 for i in range(3)]
k = 0
for i in range(3):
for j in range(3):
keyMatrix[i][j] = LETTERS.find(key[k])
k = k+1
# generate column vector for the inputted message
# As key vector is 3x3, the message vectors will be of size 3x1
size_message = int(len(plainText) / 3)
messageMatrix = [[0] * size_message for i in range(3)]
k = 0
j = 0
while(k < size_message):
for i in range(3):
messageMatrix[i][k] = LETTERS.find(plainText[j])
j = j + 1
k = k + 1
# encrypt the plain text into cipher text using hill cipher
# C = KP mod 29
cipherMatrix = [[0] * size_message for i in range(3)]
for i in range(3):
for j in range(size_message):
cipherMatrix[i][j] = 0
for x in range(3):
#Matrix multiplication
cipherMatrix[i][j] += (keyMatrix[i][x] * messageMatrix[x][j])
# Taking mod 29 of the generated vector according to the formula
cipherMatrix[i][j] = cipherMatrix[i][j] % 29
# Generate the encrypted text from above encrypted numbered matrix
CipherText = []
k = 0
while(k < size_message):
for i in range(3):
num = cipherMatrix[i][k]
CipherText.append(LETTERS[num])
k = k + 1
print("Ciphertext:", "".join(CipherText))
| true |
1a0ec0505034f369127272a25f326f437c9ce2c6 | kjeelani/YCWCodeFiles | /Basic Warmups/basics1.py | 1,012 | 4.40625 | 4 | #Console is ----> where things are printed
print("Hello World")
print("----")
#variables are defined by one equal sign, and have a certain variable type. For now, you will work with strings and ints
#strings(words)
#ints(whole numbers)
message = "Hello World"
print(message)
x = 4
print(x)
print("----")
"""Note: Never have spaces in your variable names. Instead use underscores. new message = "Hello" is wrong. new_message = "Hello" is correct."""
#addition(+)
#subtraction(-)
#multiplication(*)
#division(/)
#exponents(**)
#modulo(remainder function)(%)
num1 = 8
num2 = 4
num3 = 36
"""Once you've solved these problems in your head, delete the hashtag in front
of the print statement"""
#Excersise 1
#print(num3 - (num2 + num1))
#Write your answer here:
#Excersise 2
#print(num3 / (num1 + num2))
#Write your answer here:
#Excersise 3
#print((num3-num1) % num1)
#Write your answer here:
print("----")
#Excersise 4: make a variable called reply and set it equal to 'The World Says Hello'
#then print it! | true |
4b1191685db24a1a1b5183b470d26d72681794ed | teachandlearn/dailyWarmups | /switch_two_variables.py | 465 | 4.15625 | 4 | # Super easy, but it might be a good activity for my students.
# Ask: show me (on paper, but better on a whiteboard) how you would swap the values of two variables.
# https://stackoverflow.com/questions/117812/alternate-fizzbuzz-questions
# Variables
var_one = 25
var_two = 35
placeholder = 0
# Switch the values
placeholder = var_one
var_one = var_two
var_two = placeholder
# output
print("Variable One: " + str(var_one))
print("Variable Two: " + str(var_two))
| true |
ad33794460a934c50149f07b36abff6dc5633557 | teachandlearn/dailyWarmups | /multiples_of_three_and_five.py | 1,074 | 4.3125 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# Warm up prompt: https://projecteuler.net/problem=1
# variables
sum_of_multiples = 0
multiples_of_three_num = 0
multiples_of_five_num = 0
multiples_of_both_num = 0
# iterating through every number up to 1000
for i in range(0, 1000):
if i % 3 == 0 and i % 5 == 0:
sum_of_multiples += i
multiples_of_both_num += 1
elif i % 3 == 0:
sum_of_multiples += i
multiples_of_three_num += 1
elif i % 5 == 0:
sum_of_multiples += i
multiples_of_five_num += 1
else:
sum_of_multiples += 0
# output
print("The sum of the multiples of three and five: " + str(sum_of_multiples))
print("The number of multiples of both three and five: " + str(multiples_of_both_num))
print("The number of multiples of only three: " + str(multiples_of_three_num))
print("The number of multiples of only five: " + str(multiples_of_five_num))
| true |
0e6709c2fb734b287082be951487108f6cb2ee22 | andrexburns/DojoProjects | /codingdojo_python/pytonoop/bikeoop.py | 589 | 4.15625 | 4 | class bike(object):
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayinfo(self):
print self.price , self.max_speed, self.miles
def ride(self):
self.miles += 10
return self
def reverse(self):
self.miles -= 5
return self
bike1 = bike(200, "50mph", 100)
bike1.ride().ride().ride().reverse().displayinfo()
bike2 = bike(300, "70mph", 150)
bike2.ride().ride().reverse().reverse().displayinfo()
bike3 = bike(500, "180mph", 150)
bike3.reverse().reverse().reverse().displayinfo()
| true |
d7a16f08027805d5bce4aa3006719027c4902a6f | NelsonDayan/Data-Structures-and-Algorithms | /Stack and Queue/Queue.py | 633 | 4.15625 | 4 | #Implementation of a queue
stack=[]
tmp_stack=[]
top=0
while True:
option=input("Choose your option:\n1.enqueue\n2.dequeue\n3.exit")
if option=="enqueue" | "2":
element=input("Enter element for insertion: ")
stack.append(element)
top+=1
print(stack)
elif option=="dequeue" | "2" :
if top==0:
print("Queue is empty")
else:
for i in range(0,top-1):
stack[i]=stack[i+1]
top-=1
stack.pop()
print(stack)
elif option=="exit" | "3":
exit(0)
else:
print("Enter a valid option: ")
| true |
93c64e96afc91df10f31b256c04585fcb14ea709 | cchauve/Callysto-Salish-Baskets | /notebooks/python_scripts/atomic_chevron.py | 1,211 | 4.15625 | 4 | # Function: For Chevron Pattern - Creates a single row of the Chevron Pattern
# Input: The height and number of colors used for the Chevron as well as the row number of the row to be created
# Output: A string containing a row of a Chevron Pattern
def create_row(height, num_colors, row_num):
# Each row of the Chevron pattern contains a certain number of plain blocks at the start of the row
st_out = (2*row_num)*'-'
# From the first color to second last, add two colored blocks followed by three plain blocks
for i in range(num_colors-1):
st_out += 2*color_list[i] + 3*'-'
# For the last color, add two colored blocks followed by the number of plain blocks the row should end with
st_out += 2*color_list[num_colors-1]+ 2*(height-row_num-1)*'-'
return(st_out)
# Function: Create Chevron Pattern
# Input: The height and number of colors used for the Chevron
# Output: A string of a Chevron pattern
def build_atomic_chevron(height, num_colors):
row = ''
st_out = ''
# Create the Chevron row by row
for i in range(height):
row = create_row(height, num_colors, i)
st_out += row + '\n'
return(st_out) | true |
91b77d715f14e5c0ce42b811eda03119b5763f22 | Malcolm-Tompkins/ICS3U-Unit5-02-Python-Area_Triangle | /area_triangle.py | 843 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on May 26, 2021
# Calculates the area of a triangle with functions
def area_of_triangle(user_base, user_height):
area = user_base * user_height / 2
print("The area of your triangle is: {:.0f}mm²".format(area))
def main():
user_input1 = (input("Enter the base of your triangle (mm): "))
user_input2 = (input("Enter the height of your triangle (mm): "))
try:
user_base = int(user_input1)
try:
user_height = int(user_input2)
area_of_triangle(user_base, user_height)
except Exception:
print("{} is not a positive integer".format(user_input2))
except Exception:
print("{} is not a positive integer".format(user_input1))
finally:
print("Done.")
if __name__ == "__main__":
main()
| true |
09119f0a6e1775a39d3987891a5c8d6e717e63db | akshaygepl1/Python-codes | /Chapter2/Word_count_unique_sorted.py | 340 | 4.1875 | 4 | # Get a list of words with their count in a sentence .
# The word should be in a sorted order alphabetically.Word should not be repeated.
# Assume space as separator for words.
User_input = input("Enter the sentence on which the operation will be performed :")
temp = list(set(User_input.split()))
t1 = temp
t1.sort()
print(t1)
| true |
1b9b8f6ff4f1d41e7dc45049f1a10a6d1d11eb49 | akshaygepl1/Python-codes | /Chapter2/Lab1.py | 285 | 4.375 | 4 | # Input a sentence and display the longest word
User_Intput = input("Enter a sentence")
Longest = ""
Length = 0
List_Of_Words = [x for x in User_Intput.split()]
print(List_Of_Words)
for i in List_Of_Words:
if(len(i)>Length):
Longest = i
print(Longest) | true |
e09b59ea41fffe88da96705f2775cb55b2930149 | bpl4vv/python-projects | /OddOrEven.py | 997 | 4.375 | 4 | # Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
# Hint: how does an even / odd number react differently when divided by 2?
# Extras:
# 1. If the number is a multiple of 4, print out a different message.
# 2. Ask the user for two numbers: one number to check (call it num) and one number to divide by (check).
# If check divides evenly into num, tell that to the user. If not, print a different appropriate message.
num1 = int(input("Give me a number and I will tell you if it is even or odd.\n"))
if(num1 % 4 == 0):
print(num1, "is even and is divisible by 4.")
elif(num1 % 2 == 0):
print(num1, "is even.")
else:
print(num1, "is odd.")
num = int(input("Give me another two numbers and I will tell you if the second is a factor of the first.\n"))
check = int(input())
if(num % check == 0):
print(check, "is a factor of " + str(num) + ".")
else:
print(check, "is not a factor of " + str(num) + ".") | true |
0f737d2e2c66a0bce9d4318769d3794e45aad765 | fabianomalves/python_introduction | /exerc_307.py | 277 | 4.28125 | 4 | """
Create a code asking two integers. Print the sum of these numbers.
"""
number1 = int(input('Type the first integer number: '))
number2 = int(input('Type the second integer number: '))
sum_of_numbers = number1 + number2
print('The sum of two numbers are: ', sum_of_numbers)
| true |
fb4f176453ce41f7cf1447d255850ddc8030b4f6 | tashadanner/magic8 | /magic8.py | 997 | 4.1875 | 4 | import random
name = input('What is your name?')
question = input('What is your question?')
answer = ""
random_number = random.randint(1,11)
if random_number == 1:
answer = "Yes - definitely."
elif random_number == 2:
answer = "It is decidely so."
elif random_number == 3:
answer = "Without a doubt."
elif random_number == 4:
answer = "Reply hazy, try again."
elif random_number == 5:
answer = "Ask again later."
elif random_number == 6:
answer = "Better not tell you now."
elif random_number == 7:
answer = "My sources say no."
elif random_number == 8:
answer = "Outlook not so good"
elif random_number == 9:
answer = "Very doubtful."
elif random_number == 10:
answer = "Most likely."
elif random_number ==11:
answer = "It must remain a secret."
else:
answer = "Error"
if name == "":
print(question + ": ")
else:
print(name + " asks: " + question)
if question == "":
print("Please ask a question")
print("Magic 8-ball's answer: " + answer)
#print(random_number) | true |
e9544452230461195b198545c237d9968785ebe8 | davisbradleyj/my-class-repo | /22-ruby-python-break-outs/activities/01-python/06-Ins_List/Demo/lists.py | 832 | 4.3125 | 4 | # Create a variable and set it as an List
myList = ["Tony Stark", 25, "Steve Rodgers", 80]
print(myList)
# Adds an element onto the end of a List
myList.append("Thor")
myList.append("Thor")
myList.append("Thor Nolan")
print(myList)
# Returns the index of the first object with a matching value
print(myList.index("Thor"))
# Changes a specified element within an List at the given index
myList[3] = 85
print(myList)
# Returns the length of the List
print(len(myList))
# Removes a specified object from an List
myList.remove("Thor")
print(myList)
# Removes the object at the index specified
myList.pop()
print("popped")
print(myList)
# Creates a tuple, a sequence of immutable Python objects that cannot be changed
myTuple = ('Python', 100, 'VBA', False)
print(myTuple)
# Extra list functionality - why Python is amazing for data analysis
| true |
19c0ac5125a333fe6815e0e31c113e084bba8c10 | davisbradleyj/my-class-repo | /22-ruby-python-break-outs/activities/01-python/02-Stu_HelloVariableWorld/Unsolved/HelloVariables.py | 784 | 4.34375 | 4 | # Create a variable called 'name' that holds a string
name = "Brad"
# Create a variable called 'country' that holds a string
country = "USA"
# Create a variable called 'age' that holds an integer
age = 37
# Create a variable called 'hourly_wage' that holds an integer
hourly_wage = 50
# Calculate the daily wage for the user (assuming that user works 8 hours a day)
daily_wage = hourly_wage * 8
# Create a variable called 'satisfied' that holds a boolean
satisfied = True
# Print out "Hello <name>!"
print("hello " + name)
# Print out what country the user entered
print("hello " + country)
# Print out the user's age
print("hello " + str(age))
# With an f-string, print out the daily wage that was calculated
# With an f-string, print out whether the users were satisfied
| true |
1651dbcf9042bc8ad9ab0cb8eaf0f2811fa91cf2 | vichi99/Python | /dictionary.py | 1,109 | 4.15625 | 4 | ##############################################################################
# The program do not nothing special, only shows formatting dictionary
##############################################################################
A = {1: "one", 2: "two"}
B = {2: "dva", 3: "three"}
def transforms(A): # converts dict to list in tuple
l = []
for i in A.items():
l.append(i)
print("Converting dictionary:\n{}\n\nTo tuple:\n{}\n{}\n".format(A,
l,
"=" * 50))
def merge(A, B):
ax = A.copy()
bx = B.copy()
for key, value in bx.items():
if key in ax:
ax[key] = [ax[key], value]
else:
ax[key] = value
print(">>> A = {}\n>>> B = {}\n>>> Merge: {}\n{}\n".format(A,
B,
ax,
"=" * 50))
transforms(A)
merge(A, B)
| false |
be6e5c7ccfb3ac5b942a3d5774fcbcd61f8ce15f | JaysonGodbey/ConsoleTicketingSystem | /master_ticket.py | 1,142 | 4.1875 | 4 | SURCHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
def calculate_price(number_of_tickets):
return (number_of_tickets * TICKET_PRICE) + SURCHARGE
while tickets_remaining >= 1:
print("There are {} tickets remaining.".format(tickets_remaining))
name = input("What is your name? ")
number_of_tickets = input("Hello, {}! How many tickets would you like to buy? ".format(name))
try:
number_of_tickets = int(number_of_tickets)
if number_of_tickets > tickets_remaining:
raise ValueError("There are only {} tickets remaining.".format(tickets_remaining))
except ValueError as err:
print("Oh no, we ran into an issue. {} Please try again.".format(err))
else:
amount_due = calculate_price(number_of_tickets)
print("Your total is ${}.".format(amount_due))
proceed = input("Would you like to proceed with the purchase Y/N? ")
if proceed.lower() == "y":
print("SOLD!")
tickets_remaining -= number_of_tickets
else:
print("Thank you anyways, {}.".format(name))
print("Sorry, we are sold out of tickets.")
| true |
8e35e69ca7c1cc201119d28e2f6d5fc531579bf9 | ShawnWuzh/algorithms | /heap_sort.py | 1,149 | 4.125 | 4 | # written by HighW
# This is the source code for heap sort algorithm
class HeapSort:
def heapSort(self, A, n):
'''
Every time, we swap the root with the last node, the last node is the current largest
'''
self.build_max_heap(A, n)
while(n > 1):
A[0], A[n-1] = A[n-1], A[0]
n -= 1
self.max_heapify(A,n,0)
return A
def max_heapify(self, A, size,i):
'''
max_heapify is done from top to bottom
'''
left_child = 2 * i + 1
right_child = 2 * i + 2
max = i
if left_child < size and A[max] < A[left_child]:
max = left_child
if right_child < size and A[max] < A[right_child]:
max = right_child
if max != i:
A[i], A[max] = A[max], A[i]
self.max_heapify(A,size,max)
def build_max_heap(self, A, n):
'''
the heap is built fron bottom to top
'''
for i in range(n // 2 - 1, -1, -1):
self.max_heapify(A,n,i)
if __name__ == '__main__':
sort = HeapSort()
print(sort.heapSort([1,2,9,7,8,5,3,2],8))
| false |
f5cff0bb472b1a69b31bec58186988d1438af64b | TonyLijcu/Practica | /Prac_04/inte1.py | 336 | 4.125 | 4 | Number = []
for i in range(5):
number = int(input("Write a number: "))
Number.append(number)
print("The first number is", Number[0])
print("The last number is", Number[-1])
print("The smallest number is", min(Number))
print("The largest number is", max(Number))
print("The average of the numbers is", sum(Number) / len(Number)) | true |
0e5443af8ea48ffa7887a0e2d18c265dfa0f1d49 | liangming168/leetcode | /DFSandBacktracking/Q257_binaryTreePath.py | 1,499 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Q257 binary tree path
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
"""
'''
method dfs
to check whether a node is leaf, if not root.left and not root.right
since, when don't check whether root is None, so when go left and right, we use if root.left, if root.right
and after each dfs since we use append to curr, we should pop curr
time: O(n), traversal every node once
space: O(n)
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.res = []
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
self.dfs(root,[])
return self.res
def dfs(self,root,curr):
if not root.left and not root.right:
curr.append(str(root.val))
self.res.append('->'.join(curr[:]))
return
curr.append(str(root.val))
if root.left:
self.dfs(root.left,curr)
curr.pop()
if root.right:
self.dfs(root.right,curr)
curr.pop() | true |
dbd656bbc0123cd6da290253433f10d7d05e4cf4 | liangming168/leetcode | /heap/Q114_flattenBT2SingleList.py | 832 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Q114 flatten BT into a linked lsit
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
'''
recursion preorder traversal
1.2.3.4.5.6 is inorder travers
6.5.4.3.2.1
go right, then left, final root, keep the track of prev node, curr node
'''
class Solution:
def __init__(self):
self.prev = None
def flatten(self, root):
if not root:
return None
self.flatten(root.right)
self.flatten(root.left)
root.right = self.prev
self.prev = root
root.left = None | true |
974d05f7d5514d19dcc3ab8038ad3fedd794c321 | ashwinchidambaram/PythonCode | /projecteuler/Question3.py | 1,696 | 4.125 | 4 | # Ashwin Chidambaram ##
# Task: What is the largest prime factor of the number 600851475143 ##
######################################################################
import math
# [1] - Create a list to hold the factors of 600851475143
factorList = []
# Create a variable to store the number that will be divided into 600851475143 to see if it's a factor
num = 2
# [2] - Create a while loop to iterate till it reaches half the value of the original number
while num <= (math.sqrt(600851475143)):
# Take the mod of 600851475143 % num and check if = 0. If true, then its a factor. If false, not a factor
if 600851475143 % num == 0:
# Add number to list
factorList.append(num)
num += 1
else:
num += 1
# [3] - Check if factor is prime or not
# Set base value of prime to false as a method of check
prime = False
# Create a while loop that will determine the largest prime from the factor list
while prime == False:
# Get largest factor by popping last value
factor = factorList.pop()
# Set divisor to base value of 2
num = 2
# Create a while loop to itterate through dividends till it reaches point of x-1, however if a value is triggered by then, break
while num != factor - 1:
prime = True
# Create a variable to store the mod of factor, num
check = factor % num
# Check if mod value = 0, since that means their is an even quotient
if check == 0:
prime = False
break # Break from loop
# Increment divisor
num += 1
# Print largest prime value
print('The largest prime factor is: {}'.format(factor))
| true |
e38b587fdfb591b5ef8726e9cd0506bdb97cecf4 | KamrulSh/Data-Structure-Practice | /linked list/palindromLinkedList.py | 2,991 | 4.21875 | 4 | # Function to check if a singly linked list is palindrome
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def appendAtHead(self, value):
newNode = Node(value)
newNode.next = self.head
self.head = newNode
def printList(self):
print("List:")
current = self.head
while current:
print(current.data, end=' -> ')
current = current.next
print("null")
def printListOp(self, head):
current = head
while current:
print(current.data, end=' -> ')
current = current.next
print("null")
# method 1 -> stack method
# Time and space complexity: O(n)
def checkPalindromUsingStack(self):
stack = []
current = self.head
while current:
stack.append(current.data)
current = current.next
current = self.head
isPalindrome = True
while current:
peak = stack.pop()
if peak == current.data:
isPalindrome = True
else:
isPalindrome = False
break
current = current.next
if isPalindrome:
print("List is palindrome\n")
else:
print("List is not palindrome\n")
# METHOD 2 (By reversing the list)
# Time Complexity: O(n) Auxiliary Space: O(1)
def checkPalindromByReverseList(self):
# find middle element
slow = fast =self.head
self.printList()
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# reverse the 2nd half list
middleHead = slow
previous = None
tempHead = None
while middleHead:
tempHead = middleHead.next
middleHead.next = previous
previous = middleHead
middleHead = tempHead
# for print start
reverse = previous
print("After reverse:")
self.printListOp(reverse)
# for print end
current = self.head
isPalindrome = True
while current and reverse:
if current.data != reverse.data:
isPalindrome = False
break
else:
current = current.next
reverse = reverse.next
if isPalindrome:
print("List is palindrome")
else:
print("List is not palindrome")
if __name__ == "__main__":
llist = LinkedList()
nlist = [30, 40, 50, 60, 50, 40, 30]
for i in range(len(nlist)):
llist.appendAtHead(nlist[i])
llist.checkPalindromByReverseList()
print("-"*50)
ll = LinkedList()
sl = [ 'a', 'b', 'a', 'c', 'a', 'b', 'a' ]
for i in range(len(sl)):
ll.appendAtHead(sl[i])
ll.printList()
ll.checkPalindromUsingStack()
| true |
69cdb419707c0d1429e6796e5b85569b12e0d321 | NAyeshaSulthana/11morning | /conditionalstatements.py | 1,986 | 4.1875 | 4 | #conditional statements-statements will be executed based on conditions..
#3 statements:
#1-if statement
#2-if else statement
#3-if elif else statement
#If statement:
#block of statement in python is represented using indentation
"""
Syntax:-
#it automatically takes space in next line with 4 spaces after if condition
if condition:
statements
"""
#a=int(input("enter the value"))
#print(type(a))
#print(a)
#if a>50:
#print("value entered is graterthan 50")
#print("Else Block")
#IF-ELSE STATEMENT
"""
#if-elif-else
""
if condition:
statement
elif condition:
statement
elif condition:
statement
else
statement
"""
marks=int(input("enter your marks:-"))
if marks>70:#if condition can be used once
print("you dot distinction!")
elif marks>60 and marks<=70:
print("you got first class!")
elif marks>50 and marks<=60:#elif condition can be used any no. of times
print("you got second class!")
else:
print("you are just passed!")
#if-else
a=int(input("enter thevalue:-"))
print(type(a))
if a>50:
print("value entered is greater than 50")
else:
print("value is lesser than 50")
###############################################
##################################################
############PRACTICE
#conditional statements
#3 statements
#if
#if else
#if elif else
#if
a=int(input("enter the value"))
print(type(a))
print(a)
if a>50:
print("value entered is greater than 50")
#print("ELSE BLOCK")
#IF ELIF ELSE
"""
if condition:
statement
elif:
statement
elif:
statement
else:
statement
"""
marks=int(input("enter your marks:"))
if marks>70:
print("you got distinction")
elif marks>60 and marks<=70:
print("you got 1st class")
elif marks<50 and marks<=60:
print("you got 2nd class")
else:
print("you are just passs")
a=int(input("enter value:"))
print(type(a))
if a>50:
print("value entered is greater than 50")
else:
print("value entered is less than 50")
| true |
1ba8750f36f3187b97c0e6f34785839e4ac56864 | NAyeshaSulthana/11morning | /day2.py | 842 | 4.125 | 4 | print("5"+"5")
print("aye"+"sha")
print(5+5)
print(5-3)
print(5/2)
print(5%2)
print(5//2)
print(5**3)
print(1, 2, 3, "4", 5.0)
print(1, 2, 3, "4", 5.0, "hello")
print("hello")
print("\n")
print(3)
print("hello", end="\t")
print(3)
print("hello", end="")
print(3, end =" ")
print(5)
#boolean data type
a=True
b=False
print(type(a))
print(type(b))
#comparision operation
#==, >, <, >=, <=, !=
#NOTE=comparision operation always returns output
print(5==5)
print(5>2)
print(5<2)
print(6>=6)
print(6<=7)
print(6!=6)
#things which are not 0 or none are True
#0 or none is false
#a=True
#and,or
print(True and True and False)#all should be True
print(True or False)#all should be True
x=3000
print(x>1500 and x<3000)
print(x%2==0 or x%5==0)
# isinstance
a=5
print(isinstance("a",str))
#Data Structures
| true |
93433b16fca42c2f452beae88797b761655770cf | wissenschaftler/PythonChallengeSolutions | /Level 3/charbychar.py | 2,445 | 4.15625 | 4 | # The URL of this level: http://www.pythonchallenge.com/pc/def/equality.html
# Character by character processing,without using re module
# Written by Wei Xu
strFile = open("equality.txt",'r') # equality.txt is where the data is
wholeStr = strFile.read()
countLeft = 0 # the number of consecutive capital letters on the left side of a small letter
countRight = 0 # the number of consecutive capital letters on the right side of a small letter
left3 = False # whether there are 3 consecutive capital letters on the left side of the considered small letter
leftCap = False # whether the previous letter is capital
resultTemp = [] # preparatory list for the final result
result = [] # the final result
for i in wholeStr:
# if i is capital and its left letter is small
if (not leftCap) and (65 <= ord(i) <= 90):
leftCap = True
# If i's left small letter is preceded by three consecutive capital letters,then that small letter is our candidate
# and we start to count the number of consecutive capital letters on its right
# Otherwise we treat i as the capital letter on the left side of the next small letter
if left3:
countRight += 1
else:
countLeft += 1
# if i is capital and its left letter is capital
elif leftCap and (65 <= ord(i) <=90):
if left3 and (countRight < 3):
countRight += 1
# if countRight>3,then stop counting countRight since it would be useless,but instead assign its value to countLeft
elif countRight == 3:
countLeft = countRight
countRight += 1 # simply to bypass the check of countRight == 3 in Line 37
countLeft += 1
resultTemp.append('0') # the 0's and its left letter will be ignored when getting the final result
else:
countLeft += 1
# if i is small
elif (122 >= ord(i) >= 97):
leftCap = False
if (countLeft == 3) or (countRight == 3):
left3 = True
resultTemp.append(i)
elif left3:
left3 = False
resultTemp.append('0')
countLeft = 0
countRight = 0
# get result from resultTemp,i.e. ignoring 0's and its preceding single small letter
prev='0'
for j in resultTemp:
if (j != '0') and (prev != '0'):
result.append(prev)
prev = j
if (prev != '0') and (countRight == 3):
result.append(j)
print ''.join(result)
| true |
eb6dd48e283948cc5c9965cbf6589ad1bea4b2a9 | jitudv/python_programs | /stringTest.py | 392 | 4.15625 | 4 | print("this is String test py ")
name ='jitu'
sortintro = " hii this jitu yadav from khargone "
sumary =""" hhii thi is jitu yadav and jit
is a python developer and he is working on
java and datascince technologies """
print(name)
print(sortintro)
print(sumary)
sortintro = str.upper(sortintro)
print(sortintro)
count="jitu"
sortintro=str.replace("jitu","JITU",count)
print(sortintro) | false |
18e747d7699378d5b3ac278945484c6ed0f22431 | RajendraBhagroo/Algorithmic_Thinking | /Algorithms_Sedgewick_Python/Chapter_1/binary_search.py | 2,646 | 4.4375 | 4 | import unittest
# Lists MUST Be Sorted Prior To Use
# Name: Binary Search [Iterative]
# Runtime Analysis: O(Log N)
def binary_search_iterative(list_: "List Of Integers", key: "Value To Find Within List") -> "Index Of Value Within List If Exists, Or -1":
"""
Searches For Key Within List.
If The Search Is Successful, The Algorithm Will Return The Index Where The Key Was Found Within The List.
Otherwise It Will Return -1 For Not Found.
"""
low = 0
high = len(list_) - 1
while (low <= high):
mid = low + (high - low) // 2
if (key < list_[mid]):
high = mid - 1
elif(key > list_[mid]):
low = mid + 1
else:
return mid
return -1
# Name: Binary Search [Recursive]
# Runtime Analysis [Stack Space]: T(N) = T(N-2) + c
# Runtime Analysis: O(Log N)
def binary_search_recursive(list_: "List Of Integers", key: "Value To Find Within List") -> "Index Of Value Within List If Exists, Or -1":
"""
Searches For Key Within List.
If The Search Is Successful, The Algorithm Will Return The Index Where The Key Was Found Within The List.
Otherwise It Will Return -1 For Not Found.
"""
return _binary_search_recursive(list_, key, 0, len(list_) - 1)
# Private Function [Weak Convention]
def _binary_search_recursive(
list_: "List Of Integers",
key: "Value To Find Within List",
low: "Current Lower Search Bound",
high: "Current UpperSearch Bound"
)-> "Index Of Value Within List If Exists, Or -1":
"""Private Function Used To Maintain Transparency Of Binary Search To Caller"""
if(low > high):
return -1
mid = low + (high - low) // 2
if(key < list_[mid]):
return _binary_search_recursive(list_, key, low, mid - 1)
elif(key > list_[mid]):
return _binary_search_recursive(list_, key, mid + 1, high)
else:
return mid
class Test(unittest.TestCase):
def test_binary_search_iterative(self):
self.assertEqual(
binary_search_iterative(
[3, 6, 10, 13, 17, 28], 17
), 4)
self.assertEqual(
binary_search_iterative(
[3, 6, 10, 13, 17, 28], 12
), -1)
# Same Test Case To Prove Transparency Between Iterative & Recursive
def test_binary_search_recursive(self):
self.assertEqual(
binary_search_iterative(
[3, 6, 10, 13, 17, 28], 17
), 4)
self.assertEqual(
binary_search_iterative(
[3, 6, 10, 13, 17, 28], 12
), -1)
if __name__ == "__main__":
unittest.main()
| true |
42654e0f5ceee9de50fed1a4a44617c870d0d6bb | raosindhu/lpth | /Ex16.py | 1,111 | 4.25 | 4 | from sys import argv
print len(argv)
script, filename = argv
print argv[0]
print argv[1]
print "I'M GOING TO ERASE THE FILE"
raw_input("?")
print "OPENING THE FILE..."
target = open(filename, 'w')
print "Now i'm entering three lines"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "write these lines to the file"
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n") # write all 3 lines each in a new line at a time to the file
#target.write(line1 + "\n")
#target.write("\n")
#target.write(line2 + "\n")
#target.write("\n")
#target.write(line3 + "\n")
print "close the file"
target.close()
print "Now i'm opening the file in append mode"
target = open(filename, 'a')
#print "Truncating the file"
#target.truncate()
print "Now i'm entering three lines"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "write these lines to the file"
target.write(line1 + "\n")
#target.write("\n")
target.write(line2 + "\n")
#target.write("\n")
target.write(line3 + "\n")
print "close the file"
target.close() | true |
7fdf58c747a7fcf276e9d2c0e51159c2d40c89bf | raosindhu/lpth | /Ex20.py | 867 | 4.25 | 4 | from sys import argv
script, input_file = argv
def print_file(f): # function to print the file
print f.read()
def rewind(f): # function to rewind the already read file to first line
f.seek(0)
def print_line(no_of_lines, f): # print specific number of lines from a file
print no_of_lines, f.readline(), # readline reads a single line from the file and returns \n at the end of the line. this adds space betweent he lines printed by this function.
# comma is added to remove the extra line between the printed lines
input_open = open(input_file)
print "1.print the entire file"
print_file(input_open)
print "2.rewind the file \n"
rewind(input_open)
print "3.print each single line"
current_line = 1
print_line(current_line, input_open)
current_line += 1
print_line(current_line, input_open)
current_line += 1
print_line(current_line, input_open)
| true |
d2b3371f40e60f971cfcf48c4f60ad990bccbb28 | deepprakashp354/python | /python/class/Avengers.py | 1,131 | 4.1875 | 4 | class Avenger:
avengersCount=0
def __init__(self, name, power):
Avenger.avengersCount +=1
self.name = name
self.power = power
def howMany():
print("Total Avengers %d" % Avenger.avengersCount)
def getName(self):
print("Avenger Name : "+self.name+" Have power "+self.power)
hulk=Avenger("Hulk","Angryness")
print(hulk.name)
print(hulk.power)
hulk.getName()
hulk.size="Very Big" #An attribute i being added explicitly
print(hulk.size)
#del hulk.power #An attribute power is being deleted
#print(hulk.power)
#This will show an error as the attribute power of hulk has been deleted
Avenger.howMany()
print("\n######################################\n")
ironMan=Avenger("ironMan", "suite")
Avenger.howMany()
ironMan.getName()
print(ironMan.name)
print(ironMan.power)
print("\n#######################################\n")
print("AvengersCount = ", Avenger.avengersCount)
print(getattr(hulk,"power")) #print the value of attribute brought by getattr() method
setattr(hulk,"power","more angry") #sets the new value to the attribute
print(getattr(hulk,"power")) #prints the new value brought from the getattr() method | true |
008a37d2233d0170b3344dd89a32496549e0ece7 | Notch1/Python_courses_H_Augustin | /Course #2 (Python Data Structures)/assignment_8.4_words.py | 538 | 4.4375 | 4 | # Open the file romeo.txt and read it line by line. For each line, split the line into a list of words
# using the split() method. The program should build a list of words. For each word on each line check to see
# if the word is already in the list and if not append it to the list. When the program completes,
# sort and print the resulting words in alphabetical order.
fname = open("romeo.txt")
words = list()
for line in fname.read().split():
if line not in words:
words.append(line)
words.sort()
print(words)
| true |
6e2aeb52ebc3c8faf21237f54523fa3c7334a91d | KarlCF/python-challenge | /03-python/for.py | 337 | 4.1875 | 4 | cardapio = ['Carne', 'Queijo', 'Frango', 'Calabresa', 'Pizza', 'Carne Seca']
print ('')
print ('---')
print ('')
for recheio in cardapio:
print (f'Recheio de pastel sabor {recheio}')
# Code below only to show that letters are "lists"
# for letter in recheio:
# print (letter)
print ('')
print ('---')
print ('')
| true |
e6550e88fa106027391080eb859e9a1e1302a394 | GonzaloBZ/python_teoria | /clase2/c2_12.py | 1,075 | 4.125 | 4 | # Necesitamos procesar las notas de los estudiantes de este curso. Queremos saber:
# ¿cuál es el promedio de las notas?
# ¿cuántos estudiantes están por debajo del promedio?
def menores_al_promedio(prom, lista):
"""Esta función retorna la cantidad de alumnos con
notas por debajo del promedio."""
tot = 0
for nota in lista:
if nota < prom:
tot += 1
return tot
def leer_notas():
"""Esta función retorna una lista con notas de estudiantes."""
liszt = []
nota = int(input("Ingrese una nota: "))
while nota != -1:
liszt.append(nota)
nota = int(input("Ingrese una nota: "))
return liszt
def promedio(lista):
"""Esta función retorna el promedio de notas de los estudiantes."""
total = 0
for nota in lista:
total += nota
return total / len(lista)
lista = leer_notas()
prom = promedio(lista)
print(f"El promedio de las notas de todos los alumnos es: {prom}")
print(
f"Cantidad de alumnos cuyas notas son menores al promedio: {menores_al_promedio(prom, lista)}"
)
| false |
468cdcc5d427ba6633fcabcab2a26b439d348bd6 | an5558/csapx-20191-project1-words-an5558-master | /src/letter_freq.py | 1,844 | 4.125 | 4 | """
CSAPX Project 1: Zipf's Law
Computes the frequency of each letter across the total occurrences of all words over all years.
Author: Ayane Naito
"""
import argparse
import sys
import os
from src import words_util
import numpy as np
import matplotlib.pyplot as plt
def main():
"""
Adds positional and optional arguments that allow the user to specify whether the user would like the
calculated letter frequencies to be returned via standard output or plotted using matplotlib. Runs the
methods needed to read the given file and calculate letter frequency, then returns the result based on
what the user specifies.
:return: None
"""
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="a comma separated value unigram file")
parser.add_argument("-o", "--output", help="display letter frequencies to standard output", action="store_true")
parser.add_argument("-p", "--plot", help="plot letter frequencies using matplotlib", action="store_true")
args = parser.parse_args()
if os.path.isfile(args.filename):
letters, sum_total_letters = words_util.read_letters(args.filename)
letter_freq = words_util.calc_freq_letters(letters, sum_total_letters)
if args.output:
for entry in letter_freq:
print(entry[0] + ": " + str(entry[1]))
if args.plot:
x = []
y = []
for entry in letter_freq:
x.append(entry.name)
y.append(entry.freq)
plt.bar(x, y, width=0.8)
plt.title("Letter Frequencies: " + str(args.filename))
plt.xlabel("Letters")
plt.ylabel("Frequency")
plt.show()
else:
sys.stderr.write("Error: " + str(args.filename) + " does not exist!")
if __name__ == '__main__':
main() | true |
d05438425a192b47b8fdf6edef3bcf6c575d71f5 | jason-jz-zhu/dataquest | /Data Scientist/Working With Large Datasets/Spark DataFrames.py | 2,886 | 4.25 | 4 | ### Unlike pandas, which can only run on one computer, Spark can use distributed memory (and disk when necessary)
### to handle larger data sets and run computations more quickly.
### Spark DataFrames allow us to modify and reuse our existing pandas code to scale up to much larger data sets.
# step1
### Print the first four lines of census_2010.json
f = open('census_2010.json')
for i in range(4):
print(f.readline())
### The Spark SQL class is very powerful.
### It gives Spark more information about the data structure we're using and the computations we want to perform.
### Spark uses that information to optimize processes.
# step2
### use Spark SQL to read json file and put it into Spark dataframe
# Import SQLContext
from pyspark.sql import SQLContext
# Pass in the SparkContext object `sc`
sqlCtx = SQLContext(sc)
# Read JSON data into a DataFrame object `df`
df = sqlCtx.read.json("census_2010.json")
# Print the type
print(type(df))
# step3
### Call the printSchema() method on the Spark DataFrame df to display the schema that Spark inferred.
df.printSchema()
# step4
### Use the show() method to print the first five rows of the DataFrame.
df.show(5)
# Output
### +---+-------+-------+-------+----+
### |age|females| males| total|year|
### +---+-------+-------+-------+----+
### | 0|1994141|2085528|4079669|2010|
### | 1|1997991|2087350|4085341|2010|
### | 2|2000746|2088549|4089295|2010|
### | 3|2002756|2089465|4092221|2010|
### | 4|2004366|2090436|4094802|2010|
### +---+-------+-------+-------+----+
# step5
### Print the age value for each row object in first_five.
first_five = df.head(5)
for line in first_five:
print(line.age)
# Pandas DataFrame
df['age']
df[['age', 'males']]
# Spark DataFrame
df.select('age')
df.select('age', 'males')
# step6
### Select the age, males, and females columns from the DataFrame and display them using the show() method.
df[['age', 'males', 'females']].show()
# is equal to
df.select('age', 'males', 'females').show()
# step7
### Use the pandas notation for Boolean filtering to select the rows where age is greater than five.
five_plus = df[df['age'] > 5]
five_plus.show()
# step8
### Find all of the rows where females is less than males, and use show() to display the first 20 results.
df[df['females'] < df['males']].show()
### we can convert a Spark DataFrame to a pandas DataFrame using the toPandas() method.
### Converting an entire Spark DataFrame to a pandas DataFrame works just fine for small data sets.
### For larger ones, though, we'll want to select a subset of the data that's more manageable for pandas.
# step9
### Use the toPandas() method to convert the Spark DataFrame to a Pandas DataFrame, and assign it to the variable pandas_df.
### Then, plot a histogram of the total column using the hist() method.
pandas_df = df.toPandas()
pandas_df['total'].hist() | true |
216e8d088b33babbb87e859c43724aea30baf6d9 | jason-jz-zhu/dataquest | /Data Engineer/3.Algorithms And Data Structures/sort alg.py | 757 | 4.15625 | 4 | def swap(array, pos1, pos2):
store = array[pos1]
array[pos1] = array[pos2]
array[pos2] = store
def selection_sort(array):
for i in range(len(array)):
lowest_index = i
for z in range(i, len(array)):
if array[z] < array[lowest_index]:
lowest_index = z
swap(array, lowest_index, i)
def bubble_sort(array):
swaps = 1
while swaps > 0:
swaps = 0
for i in range(len(array) - 1):
if array[i] > array[i+1]:
swap(array, i, i+1)
swaps += 1
def insertion_sort(array):
for i in range(1, len(array)):
j = i
while j > 0 and array[j - 1] > array[j]:
swap(array, j, j-1)
j-=1
| false |
b36f1a7aa9c1035c6a5291af765138862dcbf9f5 | blafuente/Python | /inputFromUsers.py | 260 | 4.375 | 4 | # Getting input from users
# For python 3, it will be input("Enter your name")
name = input("Enter your name: ")
age = input("Enter your age: ")
# Python 2, uses raw_input()
# name = raw_input("Enter your name: ")
print("Hello " + name + ". You are " + age) | true |
4f157f649af3d4de3cdcc6b7dc60b27785d68ef4 | chrispy124/210CT-Coursework | /Question 6.py | 417 | 4.15625 | 4 | def WordRev (Words) : #defines the function
WordsL = len(Words) #variable is equal too length of 'words'
if WordsL == 1:
return Words #if only one word is given then it will only print that word
else:
return [Words[-1]]+ WordRev(Words[:-1]) #calls the function to reorder
ListInput = ["this", "is", "awesome"] #list for reverse
print (WordRev (ListInput)) #Print the words swapped round
| true |
6c6a9ae9d46a966a8426ec143e186bbad5645976 | huang147/STAT598Z | /Lecture_notes/functions.py | 1,697 | 4.625 | 5 | # Usually we want to logically group several statements which solve a
# common problem. One way to achieve that in Python is to use
# functions. Below we will show several features of functions in Python.
# Some examples are from: http://secant.cs.purdue.edu/cs190c:notes09
# A simple function definition begins with the keyword def followed by
# name of the function followed by the arguments to the function in
# paranthesis. Also note the : and the indentation. Python is sensitive
# to indentation!
def hello_world():
print "hello world"
return
hello_world()
# We can customize the behavior of our functions by using parameters
def greet(person):
print "Hello " + person
print "How are you?"
return
greet("vishy")
greet("mark")
greet(1)
def mean(a, b):
c=(a+b)/2.0
return c
d=mean(2, 3)
print d
mean(2, 3)
# invoking the function
print mean(3, 4)
print mean(5, 9)
def pass_by_value(a):
a=20
return
b=10
print "before calling pass_by_value:", b
pass_by_value(b)
print "after calling pass_by_value:", b
a=15
print "before calling pass_by_value:", a
pass_by_value(a)
print "after calling pass_by_value:", a
def multiple_args_return(a):
b=2*a
c=3*a
return b, c, "hello"
x=10
y,z,a=multiple_args_return(x)
print y, z, a
def named_args(a,b):
return b+2*a
named_args(b=10,a=12)
named_args(a=12,b=10)
def default_args(a, b=10):
return b+2*a
default_args(12, 1)
default_args(12)
# This example shows recursion that is the ability of a function to call
# itself
def fibonacci(n):
if n>1:
return fibonacci(n-1)+fibonacci(n-2)
else:
return n
print fibonacci(1)
print fibonacci(5)
print fibonacci(10)
| true |
1f57de85dadeadecc1edb497d4a173c3f7c5a873 | huang147/STAT598Z | /HW/HW1/stat598z_HW1_Jiajie_Huang/hw1p3.py | 1,138 | 4.21875 | 4 | #!/opt/epd/bin/python
from random import randint
print "I have a card in mind. Let's see if you are smart."
# randomly generate the sign (an integer in 1-4) and number (an integer in 1-13)
sign = randint(1, 4)
number = randint(1, 13)
# first guess the sign
while 1: # make sure the guessing goes on until get to the right answer
a = raw_input("Enter your guess for the sign(integer, 1-4):")
a = int(a)
if a < 1 or a > 4:
print "Your guess should be an integer between 1 and 4!"
elif a == sign:
print "Bingo!"
break # jump out of the 1st while loop and finish guessing sigh
elif a > sign:
print "Sorry your guess is too high"
else:
print "Sorry your guess is too low"
print "Now guess the number."
# next guess the number
while 1: # make sure the guessing goes on until get to the right answer
b = raw_input("Enter your guess for the number(integer, 1-13):")
b = int(b)
if b < 1 or b > 13:
print "Your guess should be an integer between 1 and 13!"
elif b == number:
print "Bingo!"
break
elif b > number:
print "Sorry your guess is too high"
else:
print "Sorry your guess is too low"
| true |
ec54838c3ea396310dedc64b80028450c136e346 | jawaff/CollegeCS | /CS111_CS213/SimpleEncryptDecrypt/encrypt-decrypt.py | 2,205 | 4.34375 | 4 | '''
program: encryption and decryption
author:Jake Waffle
Encrypt and decrypt lower and uppercase alphabets
1. Constants
none
2. Input
filename
distance
filename2
condition
filename3
3. Computations
Encrypting a message
Decrypting a message
4. Display
encrypted message
decrypted message
'''
#Gather Input
filename = raw_input("Enter the filename of the file you wish to encrypt: ")
distance = input("How much do you want to shift the message by? ")
filename2= raw_input("Enter the filename of the file you wish to write to.\n(If the file doesn't exist it will be created in the directory of this py file): ")
#Open the file that is to be encrypted, then close it
f = open(filename,'r')
message = f.read()
f.close()
#initialize variable
eMessage = ""
#Encrypt message
for i in message:
ordVal = ord(i)
cipherVal = ordVal + distance
#Checking to see if newline char
if ordVal == 10:
#This char doesn't conform to the range of chars that I wanna deal with
#So I'm not encrypting it
cipherVal = 10;
elif cipherVal > 126:
cipherVal = 32 + distance - (126 - ordVal + 1)
eMessage += chr(cipherVal)
#Print the altered message and write it to the corresponding file
print "This is your encrypted message:\n" + eMessage
f = open(filename2,'w')
f.write(eMessage)
f.close()
#Ask to decrypt current eMessage or to use another file
condition = raw_input("Would you like to decrypt and display the previous decrypted file?\n" + "(Enter y or n): ")
#If the user chooses to use another file to decrypt, then we need to ask for input, close the current file,
#open the new file with the new filenameand assign the contents to variable eMessage
if condition == 'n':
filename3 = raw_input("Enter the filename of the file you wish to decrypt: ")
f.close()
f = open(filename3,'r')
eMessage = f.read()
#Decrypt
dMessage = ""
for i in eMessage:
ordVal = ord(i)
cipherVal = ordVal - distance
if ordVal == 10:
cipherVal = 10
elif cipherVal < 32:
cipherVal = 126 - (distance - (ordVal - 32 + 1))
dMessage += chr(cipherVal)
print "Your decrypted message is:\n" + dMessage
| true |
3fb0005d04e5c254ee42b9203dd79520a1aaa630 | jawaff/CollegeCS | /CS111_CS213/ArtGeneration/Ch7Proj4.py | 1,809 | 4.1875 | 4 | '''
Author:Jacob Waffle, Carey Stirling
Program:Ch7 project4
Generating a piece of art
Constants
width
height
Inputs
level
Compute
pattern() directs the drawing of the squares
Display
Shows the generated picture
'''
from turtlegraphics import Turtle
import random
def fillSquare(turtle, oldX, oldY, width, height):
'''An abstract function for drawing a filled in square!'''
#Random colors!
turtle.setColor(random.randint(0,255),random.randint(0,255),random.randint(0,255))
#The arguments should be floats because of the division of stuff
oldY = int(oldY)
oldX = int(oldX)
height = int(height)
width = int(width)
#For all of the y points implied by arguments
for y in xrange(oldY, oldY-height,-1):
turtle.up()
#Move to the starting x position
turtle.move(oldX,y)
turtle.setDirection(0)
turtle.down()
#Draw a line equal in length to the width of the rectangle
turtle.move(width)
def pattern(turtle, x, y, width, height, level):
'''The recursive function that directs the drawing of the pretty squares!'''
if level > 0:
#Not done yet
pattern(turtle,x+(width/3)-1,y-(height/3), 2*(width/3)+1, 2*(height/3), level -1)
if level%2 == 0:
#Horizontal dominance
fillSquare(turtle,x,y,width/3,height)
fillSquare(turtle,x,y,width,height/3)
else:
#Vertical dominance
fillSquare(turtle,x,y,width,height/3)
fillSquare(turtle,x,y,width/3,height)
def main():
width = 1024
height = 768
paul = Turtle(width, height)
level = raw_input("Enter a level: ")
fillSquare(paul,-512.0, 384.0, 1024.0, 768.0)
pattern(paul, -512.0, 384.0, 1024.0, 768.0, level)
raw_input("Press enter to exit: ")
main()
| true |
97ea0884f579e0eb760c7f5a4bca9d6c56fda76c | Alriosa/PythonCodesPractice | /codes/emailValid.py | 218 | 4.375 | 4 | valid_email = False
print("Enter your email")
email = input()
for i in email:
if(i=="@" and i=="."):
valid_email = True
if valid_email == True:
print("Valid Email")
else:
print("Invalid Email")
| true |
1b364cb1a13f9c5c436de59679579f197ed72808 | erickzin10/python | /estrutura-sequencial/calc-inteiro-real.py | 720 | 4.28125 | 4 | # -*- coding: latin1 -*-
"""Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
1. O produto do dobro do primeiro com metade do segundo .
2. A soma do triplo do primeiro com o terceiro.
3. O terceiro elevado ao cubo."""
int1 = raw_input("Digite o primeiro inteiro: ")
int2 = raw_input("Digite o segundo inteiro: ")
real = raw_input("Digite um numer real: ")
produto = (int(int1) * 2) * (int(int2) / 2)
soma = (int(int1) * 3) + float(real)
potencia = float(real)**3
print("Produto do dobro do primeiro com metade do segundo: %d" % produto)
print("Soma do triplo do primeiro com o terceiro: %.2f" % soma)
print("Numero real elevado ao cubo: %.2f" % potencia)
| false |
ebf5c51d81b55acc43687cb5b5d0cdafe1df460d | ThomasMcDaniel91/cs-module-project-iterative-sorting | /src/searching/searching.py | 1,526 | 4.34375 | 4 | def linear_search(arr, target):
# Your code here
for i in range(len(arr)):
# go through the values in the list one at a time
# and check if any of them are the target value
if arr[i] == target:
return i
# once the function has run through all the values return -1
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# Your code here
# getting the limitations of the array
low = 0
high = len(arr) -1
mid = 0
# making sure that the lowest value is still lower than the highest after
# the change in the upper or lower point
while low <= high:
# set the midpoint to check for the binary search
mid = (high + low) // 2
# if the target is smaller than the middle value of the array
# we change the upper limit to the midpoint - 1 because we know
# it isn't the middle value, lets us remove 1 more value each time
# we go through
if arr[mid] > target:
high = mid -1
# if the target is larger than the midpoint, we move the midpoint
# to be the low end of our search
if arr[mid] < target:
low = mid+1
# if the midpoint is the target then we return the index of the value
if arr[mid] == target:
return mid
# once the low end becomes larger than the high end
# we know we have searched all values so return -1
# not found
return -1 | true |
9cc019b37f7e338e6b7b6e38b859fe63422dbd57 | csusb-005411285/CodeBreakersCode | /caesar-cipher-encryptor.py | 721 | 4.40625 | 4 | def caesarCipherEncryptor(string, key):
# Write your code here.
# intialize a list to store the results
encrypted_str = ''
# normalize the key by using the modulo operator
key = key % 26
unicode_val = 0
# loop through the string
for char in string:
# if the unicode value + key is greater than 122
if ord(char) + key > 122:
# calculate the updated unicode value; which is the result of the modulo operator
unicode_val = 96 + ((ord(char) + key ) % 122)
# else
else:
# calculate the new unicode value; which would unicode value + key
unicode_val = ord(char) + key
# insert the value in the results array
encrypted_str += chr(unicode_val)
# return encrypted_str
return encrypted_str
| true |
1dc02bedb8ffac742b29dece043b265e3419220e | csusb-005411285/CodeBreakersCode | /find-three-largest-numbers.py | 1,228 | 4.28125 | 4 | def findThreeLargestNumbers(array):
# Write your code here.
# init a list to store the three largest numbers
three_largest_nums = [None, None, None]
# loop through the array
for num in array:
# for each number check
# if it is greater than the last element of result list
if three_largest_nums[2] is None or num >= three_largest_nums[2]:
# move the 2nd element to the 1st index
# remove the first element
three_largest_nums[0] = three_largest_nums[1]
# move the 3rd element to the 2nd index
three_largest_nums[1] = three_largest_nums[2]
# insert the number in the 3rd index
three_largest_nums[2] = num
# else if the number is greater than the 2nd element of result list
elif three_largest_nums[1] is None or num >= three_largest_nums[1]:
# move the 2nd element to the 1st element
# remove the first element
three_largest_nums[0] = three_largest_nums[1]
# insert the number in the 2nd index
three_largest_nums[1] = num
# else if the number is greater than the 1st element
elif three_largest_nums[0] is None or num >= three_largest_nums[0]:
# override the 1st element with the number
three_largest_nums[0] = num
else:
continue
return three_largest_nums
| true |
1f21d9b77e2eb8e4b26677bef8807b9bf1bf7a97 | cvang1231/dicts-word-count | /wordcount.py | 825 | 4.3125 | 4 | from sys import argv
from string import punctuation
def count_words(filename):
"""Prints the number of shared words in a text file.
Usage: python3 wordcount.py <textfile.txt>
"""
# Open the file
file_data = open(filename)
word_dict = {}
for line in file_data:
# Tokenize data
tokenized_list = line.strip().split(" ")
# Strip away all punctuation and make lowercase
sanitized_list = [word.translate(str.maketrans('', '', punctuation)).lower() for word in tokenized_list]
# Go over each word in list and add them to the word_dict with count
for word in sanitized_list:
word_dict[word] = word_dict.get(word, 0) + 1
for key, value in word_dict.items():
print(key, value)
file_data.close()
count_words(argv[1])
| true |
a122b229a31f80fc64a9beb1421834fbca46f130 | vinaygaja/gaja | /sqr root of 3digit number.py | 419 | 4.15625 | 4 | #squareroot of a 3 digitnumber
num=625
while num!=0:
num=input('enter 3 digit number:')
num=int(num)
#print(num)
if num !=0:
if num>=100 and num<1000:
sqrt=num**0.5
print(sqrt)
num=input('enter the number:')
num=int(num)
else:
print('not a 3 digit no')
elif num==0:
print('end')
| true |
839b16b73a47c29bfcfbffdd9c8c62f15da2915e | vinaygaja/gaja | /S08Q02findingdigits&adding numbers.py | 1,140 | 4.4375 | 4 | #Question:
##Ask the user to enter a number.
##- If the number is a single digit number, add 7 to it,
## and print the number in its unit’s place
##- If the number is a two digit number, raise the number to the power of 5,
## and print the last 2 digits
##- If the number is a three digit number, ask user to enter another number.
## Add the 2 numbers and print the last 3 digits
#Code:
#main starts from here:
num=input('enter a number:')
num=int(num)
if num>=0 and num<=9:
num1=num+7
print(num1%10)
elif num>=10 and num<=99:
num2=(num**5)
print(num2%100)
elif num>=100 and num<=999:
n=input('enter another number:')
n=int(n)
num3=num+n
print(num3%1000)
##Getting output:
## RESTART: C:/Users/Administrator/Desktop/pythonexercises/S08Q02findingdigits&adding numbers.py
##enter a number:999
##enter another number:123
##122
##>>>
## RESTART: C:/Users/Administrator/Desktop/pythonexercises/S08Q02findingdigits&adding numbers.py
##enter a number:22
##32
##>>>
## RESTART: C:/Users/Administrator/Desktop/pythonexercises/S08Q02findingdigits&adding numbers.py
##enter a number:5
##2
| true |
1cebc874862b63ff8e528cc3fb2372d2517f7631 | python-elective-fall-2019/Lesson-02-Data-structures | /exercises/set.py | 1,569 | 4.3125 | 4 | # Set exercises.

1. Write a Python program to create a set.
2. Write a Python program to iteration over sets.
3. Write a Python program to add member(s) in a set.
4. Write a Python program to remove item(s) from set.
5. Write a Python program to remove an item from a set if it is present in the set.
6. Write a Python program to create an intersection of sets.

7. Write a Python program to create a union of sets.

8. Write a Python program to create set difference.

9. Write a Python program to create a symmetric difference.

10. Write a Python program to issubset and issuperset.
11. Write a Python program to create a shallow copy of sets.
Note : Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object.
12. Write a Python program to clear a set.
13. Write a Python program to use of frozensets.
14. Write a Python program to find maximum and the minimum value in a set.
15. Write a Python program to find the length of a set.
| true |
1bb9a0f3f958db4261513a6014c69f39e3b7bc11 | mwtichen/Python-Scripts | /Scripts/convert.py | 356 | 4.25 | 4 | # convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Suzie Programmer
def main():
print("This program has been modified for exercise 2.8")
fahrenheit = input("What is the Fahrenheit temperature? ")
fahrenheit = float(fahrenheit)
celsius = 5/9 * (fahrenheit - 32)
print("The temperature is", celsius, "degrees Celsius.")
main()
| false |
a532914fa167397c1814e253bb84fa340f4d168e | mwtichen/Python-Scripts | /Scripts/slope.py | 434 | 4.21875 | 4 | #calculates the slope given two points
#by Matthew Tichenor
#for exercise 3.10
def main():
print("This program calculates the slope given two points")
x1, y1 = input("Enter the first pair of coordinates: ").split(",")
x2, y2 = input("Enter the second pair of coordinates: ").split(",")
x1, y1, x2, y2 = float(x1), float(y1), float(x2), float(y2)
m = (y2 - y1)/(x2 - x1)
print("The slope of the line is",m)
main()
| true |
d18c2900fdf811aef8d8544c7feb4abcd87ce1dc | mwtichen/Python-Scripts | /Scripts/wordcount.py | 708 | 4.125 | 4 | #answer to exercise 4.18
#File wordcount.py
#by Matthew Tichenor
#need to fix number of words
import math
def main():
print("This program calculates the number of words, characters \
and lines in a file")
fileName = input("Enter a file (full file extension): ")
infile = open(fileName, 'r')
c1 = 0
c2 = 0
c3 = 0
for line in infile.readlines():
c1 = c1 + 1
sentence = line[:-1]
for string in sentence.split(' '):
a = math.ceil(len(string)/(len(string)+1))
c2 = c2 + 1 * a
for ch in string:
c3 = c3 + 1
print('There are',c1,'lines,',c2,'words and',c3,'characters.')
main()
| true |
78df2367eac7598bd2625d8ec8a42bea273aee2f | v-blashchuk/ITEA_Lessons | /Lesson 1/lesson_1_task_4.py | 1,041 | 4.28125 | 4 | # Реализовать функцию bank, которая принимает следующие аргументы:
# сумма депозита, кол-во лет и процент.
# Результатом выполнения должна быть сумма по истечению депозита.
#git push 1
try:
value_deposit = float(input('Введите сумму депозита:'))
value_years = float(input('Введите количество лет:'))
value_percent = float(input('Под какой процент желаете положить:'))
except (ValueError):
print ('Введите пожалуйста число, а не строку!')
except (TypeError):
print ('Введите пожалуйста корректное число!')
def bank(value_1, value_2, value_3):
return value_1 + value_2*(value_1*(value_3/100))
result = bank(value_deposit, value_years, value_percent)
print (f'Ваша сумма по истечению срока: {result}') | false |
36ca3751a0d2fbd8a46670aacc78f1a533838032 | Michail73/Python_hometask | /palindrom.py | 718 | 4.40625 | 4 | # function which return reverse of a string
def reverse(string):
return string[::-1]
def isPalindrome(stirng):
# Calling reverse function
rev = reverse(string)
# Checking if both string are equal or not
if (string== rev):
return True
return False
# Driver code
print("'Pls input digit to check if it is palindrom or not'\n")
string = str(input())
digit=int(string)
if digit>0:
print("подходящее число")
ans = isPalindrome(string)
if ans == 1:
print("Оно является палиндромом")
else:
print("Нет, это не палиндором")
else:
print("вы ввели отрицательное число")
| false |
72d842793cc3ca932114e0aced84f43cee062dbc | COMPPHYS-MESPANOL/comp-phys | /sorted_stars.py | 2,240 | 4.46875 | 4 | '''The function sortList takes the list 'data' and adds the elements in that list to new lists which are sorted by distance, apparent brightness, and absolute brightness. First 'counter' is intialized to 1,and the 'counter' is increased by 1
after every running of the while loop. As the 'counter' is less than 3, the while loop looks at the different
elements of the list. 1: sorts 'data' by distance into list dist_sort, and then that list is sorted into distance. A similar thing occurs for
counter=2 and counter=3. The lists are reversed at the end so that the names appears before the sorting parameter'''
'''Name, Distance, Apparent Brightness, Absolute Brightness'''
data = [
('Alpha Centauri A', 4.3, 0.26, 1.56),
('Alpha Centauri B', 4.3, 0.077, 0.45),
('Alpha Centauri C', 4.2, 0.00001, 0.00006),
("Barnard's Star", 6.0, 0.00004, 0.0005),
('Wolf 359', 7.7, 0.000001, 0.00002),
('BD +36 degrees 2147', 8.2, 0.003, 0.006),
('Luyten 726-8 A', 8.4, 0.000003, 0.00006),
('Luyten 726-8 B', 8.4, 0.000002, 0.00004),
('Sirius A', 8.6, 1.00, 23.6),
('Sirius B', 8.6, 0.001, 0.003),
('Ross 154', 9.4, 0.0002, 0.0005),
]
from pprint import pprint
distance = []
dist_sort = []
apparent = []
app_sort = []
trueB = []
trueB_sort = []
def sortList(x):
counter = 1
while counter <= 3:
if counter == 1:
distance = [[x[a][counter], x[a][0]] for a in range(0, len(x))]
dist_sort = sorted(distance)
elif counter == 2:
apparent = [[x[a][counter], x[a][0]] for a in range(0, len(x))]
app_sort = sorted(apparent)
elif counter == 3:
trueB = [[x[a][counter], x[a][0]] for a in range(0, len(x))]
trueB_sort = sorted(trueB)
counter += 1
dist_sort = [dist_sort[num][::-1] for num in range(0, len(x))]
app_sort = [app_sort[num][::-1] for num in range(0, len(x))]
trueB_sort = [trueB_sort[num][::-1] for num in range(0, len(x))]
print "Ranked by Distance:";pprint(dist_sort)
print "Ranked by Apparent Brightness:";pprint(app_sort)
print "Ranked by Absolute Brightness:";pprint(trueB_sort)
sortList(data) | true |
906caa3fafe79312bc77c8987936dc6805cb177f | Kiwinesss/100-Days-of-Python | /Day 04/rock-paper-scissors_my_version.py | 1,848 | 4.21875 | 4 | import time
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# r = rock
# p = paper
# s = scissors
print("Welcome to my game of Rock, Paper, Scissors.")
time.sleep(1) # Sleep for 2 seconds
print("Let's see if you can beat me at my own game!")
time.sleep(1)
print("If you really think you are up to it, then let's do it. Try to own me!\n")
time.sleep(1)
user_choice = input("So you start. Please choose either rock (r), paper (p) or scissors (s): ")
if user_choice != "r" and user_choice != "p" and user_choice != "s":
print("Character not allowed! Goodbye ....")
quit()
elif user_choice == "r":
print(rock)
elif user_choice == "p":
print(paper)
else:
print(scissors)
time.sleep(1)
print("Now it's my turn, let me think ..... hmmmmmm")
time.sleep(2)
print("Remember, I did not see what you chose!")
time.sleep(1)
print("Okay, I choose .....")
time.sleep(1)
computer_choice = random.choice([rock, paper, scissors])
print(computer_choice)
if computer_choice == rock and user_choice == "p":
print("Damn! You beat me! ")
elif computer_choice == paper and user_choice == "s":
print("You beat me! That was just pure luck!")
elif computer_choice == scissors and user_choice == "r":
print("Oh no you beat me! Best of three?")
elif computer_choice == rock and user_choice == "r":
print("A draw! Come on, one more time!")
elif computer_choice == paper and user_choice == "p":
print("Tied!")
elif computer_choice == scissors and user_choice == "s":
print("We have the same, let's go again!")
else:
print("Beat you sucker!!!")
| false |
d32d6f7baa8b01678300a6d99bb7d317d6b5e816 | Kiwinesss/100-Days-of-Python | /Day 07/hangman_part2.py | 647 | 4.21875 | 4 | #Coding the second part of the hangman game
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
#Testing code
print(f'Pssst, the solution is {chosen_word}.\n')
display = list() #create an empty list
for letter in (chosen_word): #create hangman grid to show the use how many words need to be guessed
display += ("_")
print(display)
guess = input("Guess a letter: ").lower() #user guesses a letter
for position in range(len(chosen_word)): #if the letter is in the word, put the letters into the grid
if chosen_word[position] == guess:
display[position] = guess
print(display)
| true |
e5b1fede2e5407983602688a614eeccc265a477c | Kiwinesss/100-Days-of-Python | /Day 04/treasure-map.py | 1,534 | 4.15625 | 4 | # 🚨 Don't change the code below 👇
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
row = int(position[0])
col = int(position[1])
row_adjusted = (row -1)
col_adjusted = (col -1)
map[row_adjusted][col_adjusted] = "X"
#Write your code above this row 👆
# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}")
##########################################
#This below was my first attemp, many lines of ugliness
##########################################
# 🚨 Don't change the code below 👇
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
coll = int(position[0])
row = int(position[1])
if row == 0 and coll == 0:
row1[coll] = "X"
elif row == 0 and coll == 1:
row1[coll] = "X"
elif row == 0 and coll == 2:
row1[coll] = "X"
if row == 1 and coll == 0:
row2[coll] = "X"
elif row == 1 and coll == 1:
row2[coll] = "X"
elif row == 1 and coll == 2:
row2[coll] = "X"
if row == 2 and coll == 0:
row3[coll] = "X"
elif row == 2 and coll == 1:
row3[coll] = "X"
elif row == 2 and coll == 2:
row3[coll] = "X"
print(f"{row1}\n{row2}\n{row3}")
| true |
91d0e99762217d718ba256b5883c3d01d27c34a8 | domspad/hackerrank | /apple_disambiguation/which_apple.py | 1,613 | 4.3125 | 4 | #!/usr/bin/env python
"""
(Basic explanation)
"""
def whichApple(text) :
"""
Predicts whether text refers to apple - the fruit or Apple - the company.
Right now only based on last appearance of word "apple" in the text
Requires: 'apple' to appear in text (with or without capitals)
Returns: 'fruit' or 'computer-company'
"""
instance, location = extractApple(text)
#coding the decision tree model
if instance[0].isupper() :
if sentenceStart(text, index) :
if isPlural(instance) :
return 'fruit'
else :
return 'computer-company'
else :
return 'computer-company'
else :
return 'fruit'
def extractApple(text) :
"""
Requires: some form of 'apple' shows up in text (i.e. capitalized, plural, possessive)
Returns: the form of the first instance found and its starting index in the text
"""
# words = text.split()
# prev = ''
# for index,word in enumerate(words) :
# #is word a variant of apple<'><s><'>?
# if word[:5].lower() == 'apple' and len(word.lower().replace("'","")) <= 6 : #like applet...
# #capital?
# if word[0].isupper() :
# +1 for company!
# #plural?
# #after end of sentence?
return 'Apple',0
def whichAppleTests() :
testcase_file = './test_cases.txt'
with open(testcase_file, 'r') as f :
num = int(f.readline())
for i in xrange(num) :
answer, text = f.readline().split('||')
assert whichApple(text) == answer
return
if __name__ == '__main__' :
whichAppleTests()
#formatted to accept Hackerrank like input
iterations = int(raw_input())
for num in xrange(iterations) :
text = raw_input()
print whichApple(text)
| true |
d1b1369bf7a1c916ea38ad802fd649b49409efb4 | DuvanDu/ProgramacionI | /Talleres/TallerClases.py | 1,440 | 4.15625 | 4 | class Torta():
def __init__(self, formaEntrada, saborEntrada, alturaEntrada):
self.forma = formaEntrada
self.sabor = saborEntrada
self.altura = alturaEntrada
def mostrarAtributos(self):
print(f'''La forma es {self.forma}
El sabor es de {self.sabor}
La altura es de {self.altura}
''')
class Estudiante():
def __init__(self, edadEntrada, nombreEntrada, idEntrada, carreraEntrada, semestreEntrada):
self.id = idEntrada
self.nombre = nombreEntrada
self.edad = edadEntrada
self.carrera = carreraEntrada
self.semestre = semestreEntrada
def estudiara(self, nombreMateria, cantidadTiempo):
print (f'Hola soy {self.nombre} estudiante de {self.carrera}, y estudiare {nombreMateria} por {cantidadTiempo} minutos')
class Nutricionista ():
def __init__(self, edadEntrada, nombreEntrada, universidadEntrada):
self.nombre = nombreEntrada
self.edad = edadEntrada
self.universidad = universidadEntrada
def IMC(self):
preguntaPeso = "Cuantos pesas en kg? : "
preguntaAltura = "Cuanto mides en metros? : "
peso = float (input (preguntaPeso))
altura = float (input (preguntaAltura))
imc = peso /(altura **2)
print (f'Hola soy {self.nombre} egresado de {self.universidad} y procedo a informarle que su IMC es de {imc}') | false |
553135378a12649427ea377e442fd0038ffc4a3b | PanMaster13/Python-Programming | /Week 4/Practice Files/Week 4, Practice 4.py | 264 | 4.21875 | 4 | x = int(input("Input the length of side1:"))
y = int(input("Input the length of side2:"))
z = int(input("Input the length of side3:"))
if x + y > z and x + z > y and y + z > x:
print("The triangle is valid")
else:
print("The triangle is not valid")
| false |
f5312edb17f4c6ff5b974058bd85deae2e9473c0 | PanMaster13/Python-Programming | /Week 6/Sample Files/Sample 7.py | 552 | 4.21875 | 4 | #Tuple - iterating over tuple
from decimal import Decimal
num = (1,2,3,4,5,6,7,8,21,18,19,54,74)
#count Odd and Even numbers
c_odd = c_even = t_odd = t_even = 0
for x in num:
if x % 2:
c_odd += 1
t_odd += x
else:
c_even += 1
t_even += x
print("Number of Even numbers:", c_even)
print("Total of Even numbers:", t_even)
print("Average of Even numbers:", round(t_even/c_even,2))
print("Number of Odd numbers:", c_odd)
print("Total of Odd numbers:", t_odd)
print("Average of Odd numbers:", round(t_odd/c_odd,2))
| true |
3ba61fff710e1bcae7063c21987ac47b7d2da4c6 | Crypto-Dimo/textbook_ex | /favourite_language.py | 1,928 | 4.34375 | 4 | favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favourite_languages['sarah'].title()
print(f"Sarah's favourite language is {language}.")
# using loop and .items() method
for name, language in favourite_languages.items():
print(f"{name.title()}'s favourite language is {language.title()}.")
# using loop and .keys() method
for name in favourite_languages.keys():
print(name.title())
# using loop without .keys() == as using .keys()
for name in favourite_languages:
print(name.title())
# how to select some keys to print
friends = ['phil', 'sarah']
for name in favourite_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favourite_languages[name].title()
print(f"\t{name.title()} I see you love {language}!")
if 'erin' not in favourite_languages.keys():
print(f"Erin, please take our poll!")
# looping in a particular order with sorted() mothod
for name in sorted(favourite_languages.keys()):
print(f"{name.title()}, thank you for taking the poll.")
# using loop for values
print("\nThe following languages have been mentioned:\n")
for language in favourite_languages.values():
print(language.title())
print("\n")
# using set() to avoid repetitions
for language in set(favourite_languages.values()):
print(language.title())
# example of a set
# languages = {'python', 'ruby', 'c'}
# nesting
favourite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favourite_languages.items():
if len(languages) > 1:
print(f"\n{name.title()}'s favourite languages are:")
for language in languages:
print(f"\t- {language.title()};")
else:
print(f"\n{name.title()}'s favourite language is {language.title()}.") | false |
58b6e992c7991394f8d8b7289c4e301fccf55996 | Andrew-McCormack/DT228-Computer-Science-Year-4-Files | /Advanced Security/Lab 1 - Caesar Cipher/CaesarCipher.py | 1,319 | 4.5 | 4 | import enchant
# PyEnchant is a package which uses dictionaries to check whether a string is a specific language
# it is used for brute forcing caesar cipher solutions where the key is unknown
def main():
while(True):
selection = raw_input('\nAre you encrypting or decrypting the message? (Enter e for encrypt, d for decrypt)\n')
if (selection.lower() == 'e'):
message = raw_input('Enter your message: ')
key = int(raw_input('What key are you shifting the message by? '))
print('\nThe encrypted message is: ' + encrypt(message, key))
elif (selection.lower() == 'd'):
message = raw_input('Enter your encrypted message: ')
key = int(raw_input('What key was the message shifted by: '))
print('\nThe decrypted message is: ' + decrypt(message, key))
def caesar(s, k, decrypt=False):
if decrypt:
k = 26 - k
r = ""
for i in s:
if (ord(i) >= 65 and ord(i) <= 90):
r += chr((ord(i) - 65 + k) % 26 + 65)
elif (ord(i) >= 97 and ord(i) <= 122):
r += chr((ord(i) - 97 + k) % 26 + 97)
else:
r += i
return r
def encrypt(p, k):
return caesar(p, k)
def decrypt(c, k):
return caesar(c, k, True)
if __name__ == "__main__":
main() | true |
5a81d14e1ac721143e7d9b258975509aad5e8ec5 | brittanyrjones/cs-practice | /postorder_tree_traversal.py | 1,022 | 4.15625 | 4 | # A class that represents an individual node in a
# Binary Tree
"""
Postorder traversal is used to delete the tree.
Please see the question for deletion of tree for details.
Postorder traversal is also useful to get the postfix expression of an expression tree.
Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation to for
the usage of postfix expression.
"""
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A function to do postorder tree traversal
def printPostorder(root):
if root:
# First recur on left child
printPostorder(root.left)
# the recur on right child
printPostorder(root.right)
# now print the data of node
print(root.val),
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "\nPostorder traversal of binary tree is"
printPostorder(root)
| true |
cada8af577da53cf9b2d6175d5c779b48bf4e695 | piolad/SudokuSolver | /SudokuSolver.py | 1,725 | 4.125 | 4 | #Made by Piotr Łądkowski
def sudoku_empty(sudoku):
for row in sudoku:
for element in row:
if type(element) is not int:
return False
return True
def solve_sudoku(sudoku):
initPossibles = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sudoku = sudoku[:]
solved = False
while not solved:
for row in range( len(sudoku) ):
for element in range( len(sudoku[row]) ):
if type(sudoku[row][element]) is not int:
possibles = initPossibles[:]
#check in grid
for rowCount in range(row - (row % 3), row - (row % 3) + 3):
for elemCount in range(element-(element%3), element-(element%3)+3):
if sudoku[rowCount][elemCount] in possibles:
possibles.remove(sudoku[rowCount][elemCount])
#check in row
for elem in sudoku[row]:
if elem in possibles:
possibles.remove(elem)
#check in column
for checkRow in sudoku:
if checkRow[element] in possibles:
possibles.remove(checkRow[element])
if len(possibles) is 1:
possibles = possibles[0]
sudoku[row][element] = possibles
solved = sudoku_empty(sudoku)
return sudoku
def print_sudoku(sudoku):
for row in sudoku:
printRow = ""
for elem in row:
printRow += str(elem)
if elem is "" or '':
printRow += "[]"
printRow += " "
print(printRow)
| false |
fbbf3273e36c33fcf41c308a514525eb84febb86 | majumdarsouryadeepta/python_20-04-21 | /Day01/condition.py | 444 | 4.21875 | 4 | # n = int(input("Enter a number: "))
# if n % 2 == 0:
# print("number is even")
# else:
# print("number is odd")
# n = int(input("Enter a number: "))
# if n % 2 == 0:
# print("number is even")
# if n > 10:
# print("number is greater 10")
# else:
# print("nummber is odd")
# if
# if
# if
# elif
# if
# else:
# else:
# if | false |
f7347d873755fe0962835c2a99d61a23d4e33b0c | adechan/School | /Undergrad/Third Year/Python 2020/Lab 6/exercise6.py | 733 | 4.28125 | 4 | # Write a function that, for a text given as a parameter, censures
# words that begin and end with voices. Censorship means replacing
# characters from odd positions with *.
import re
def function6(text):
vowels = "aeiouAEIOU"
words = re.findall("[a-zA-Z0-9]+", text)
matchedWords = []
for word in words:
r = re.findall(f"^[{vowels}][a-zA-Z0-9]*[{vowels}]$", word)
if len(r) > 0:
matchedWords.append(word)
result = []
for word in matchedWords:
for index in range(0, len(word), 2):
censoredWord = word[:index] + "*" + word[index + 1:]
word = censoredWord
result.append(censoredWord)
return result
print(function6("Anna are mere")) | true |
e27d4ffc45282bee535c3b3adab0d8d8bb49d6d7 | adechan/School | /Undergrad/Third Year/Python 2020/Lab 5/exercise5.py | 393 | 4.15625 | 4 | # Write a function with one parameter which represents a list.
# The function will return a new list containing all the numbers
# found in the given list.
def function5(list):
numbers = []
for element in list:
if type(element) == int or type(element) == float:
numbers.append(element)
return numbers
print(function5([1, "2", {"3": "a"}, {4, 5}, 5, 6, 3.0])) | true |
fd0b2dd32ecd4e1b68ece51a610abf69fcaf9fb0 | rooslucas/automate-the-boring-stuff | /chapter-10/chapter_project_10b.py | 1,248 | 4.53125 | 5 | # Chapter project chapter 10
# Project: Backing Up a Folder into a ZIP FIle
import zipfile
import os
# Step 1: Figure Out the ZIP File's Name
def backup_to_zip(folder):
# Back up the entire contents of "folder" into a ZIP file.
folder = os.path.abspath(folder) # make sure folder is absolute
# Figure out the filename this code should use based on what files already exist.
number = 1
while True:
zip_filename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zip_filename):
break
number += 1
# Step 2: Create the new ZIP file
print(f'Creating {zip_filename}...')
backup_zip = zipfile.ZipFile(zip_filename, 'w')
# Step 3: Walk the entire folder tree and compress the files in each folder
for foldername, subfolders, filenames in os.walk(folder):
print(f'Adding files in {foldername}...')
backup_zip.write(foldername)
for filename in filenames:
new_base = os.path.basename(folder) + '_'
if filename.startswith(new_base) and filename.endswith('.zip'):
continue
backup_zip.close()
print('Done.')
backup_to_zip('/Users/rosalie/developer/automate-the-boring-stuff')
| true |
291d9482b70ad8fbb43a01f84ce797f9dbdb880f | rooslucas/automate-the-boring-stuff | /chapter-3/practice_project_3.py | 400 | 4.5 | 4 | # Practice project from chapter 3
# The Collatz Sequence
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
try:
print('Enter number: ')
number_input = int(input())
while number_input != 1:
number_input = collatz(number_input)
print(number_input)
except ValueError:
print("You must enter an integer")
| true |
1b3e0e89aa35009306beed2683871768a0e88654 | TFernandezsh/Practica-6-python-tfernandez | /P6/P6-E2.py | 702 | 4.15625 | 4 | # Escribe un programa que te pida números y los guarde en una lista. Para terminar de introducir número,
# simplemente escribe “Salir”. El programa termina escribiendo la lista de números.
#
# Escribe un nombre: 14
# Escribe una otro nombre: 123
# Escribe una otro nombre: -25
# Escribe una otro nombre: 123
# Escribe una otro nombre: Salir
# Los números que has escrito son [14, 123, -25, 123]
lista = []
opened = True
while opened == True:
added = input('>>> Escribe un número:\n > ')
if added == 'Salir':
opened = False
else:
added = int(added)
lista.append(added)
print('\n>>> Los números que has escrito son %s\n' % (lista)) | false |
1ce7f62caadbf660124cadcf016748e6f53ac8e5 | RinkuAkash/Basic-Python-And-Data-Structures | /Data_Structures/Dictionary/11_list_to_dictionary.py | 250 | 4.125 | 4 | '''
Created on 11/01/2020
@author: B Akash
'''
'''
Problem statement:
Write a Python program to convert a list into a nested dictionary of keys.
'''
List=[1,2,3,4,5,6,7,8,9]
Dictionary={}
for key in List:
Dictionary[key]={key}
print(Dictionary) | true |
af59163f87a659242b8d4069903056a9a0f63c78 | RinkuAkash/Basic-Python-And-Data-Structures | /Data_Structures/Sets/09_symmetric_difference.py | 250 | 4.21875 | 4 | '''
Created on 13/01/2020
@author: B Akash
'''
'''
Problem statement:
Write a Python program to create a symmetric difference
'''
Set1={1,2,3,4,5,6}
Set2={4,5,6,7,8,9}
print("Symmetric difference of Set1 and Set2 : ",Set1.symmetric_difference(Set2)) | true |
d1f2bcda4a9dbbb59a6b7d576dba6039a4b73029 | AzeemShahzad005/Python-Basic-Programs-Practics | /Palindrome.py | 231 | 4.15625 | 4 | num=int(input("Enter the number:"))
temp=num
rev=0
while(num>0):
digit=num%10
rev=rev*10+digit
num=num//10
if(temp==rev):
print("The number is a Palindrome")
else:
print("The number is not a palindrome")
| true |
62d50bdca1c053e8fadb9381e6388cd0b7cc5ac4 | eyenpi/Trie | /src/LinkedList.py | 1,845 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def pushBack(self, data):
"""
a method that find end of a linked list and add a Node after it
:param data: data that we want to be added in linked list
:return:
"""
node = Node(data)
if self.head is None:
self.head = node
return
tmp = self.head
while tmp.next is not None:
tmp = tmp.next
"""
found the last node
"""
tmp.next = node
def delete(self, data):
"""
method to remove a data from linked list
:param data: the data that want to be removed
:return:
"""
# first check the special cases
if data == self.head.data.number:
self.head = self.head.next
return
if data == self.head.next.data.number and self.head.next.next is None:
self.head.next = None
tmp = self.head
while tmp.next is not None:
if tmp.next.data.number == data:
tmp.next = tmp.next.next
return
tmp = tmp.next
def search(self, data):
"""
search for a data in linked lsit
:param data: the data
:return:
"""
node = self.head
while node is not None:
if node.data.number == data:
return node
node = node.next
return None
def getSize(self):
"""
just for testing the collsion
:return: size of linked list
"""
node = self.head
size = 0
while node is not None:
node = node.next
size += 1
return size
| true |
f3899af018b0a0f6ab7216feec57d84342cb9d86 | Spartabariallali/Pythonprograms | /pythonSparta/tuples.py | 382 | 4.3125 | 4 | # Tuples - same as lists but they are immutable
# tuples cant be modified
# should be used when data cannot be manipulated
# tuples are declared by ()
date_of_birth = ("name","dob","passport number")
print(date_of_birth)
#convert the tuple into a string
#add your name into the list at 0 index
dob = list(date_of_birth)
print(dob)
dob.insert(0,"bari allali")
print(dob)
| true |
af1c28cd78d3ad35a5c7473bfc323900ecc325c6 | Spartabariallali/Pythonprograms | /calculatoroop/calc_functions.py | 1,059 | 4.28125 | 4 | # phase 1 - create a simple calculator
class Python_Calcalutor:
# should have add, divide,multiply,subtract and remainder
def number_subtraction(number1,number2):
return (number1 - number2)
def number_division(number1,number2):
return (number1/number2)
def number_remainder(number1,number2):
if (number1 % number2) == 0:
return True
elif (number1 % number2) != 0:
return False
def number_multiplier(number1,number2):
return (number1*number2)
def cm_to_inches():
mode = float(input(
"Enter 1 for inches to cm: \nEnter 2 for cm to inches: ")) # user input for which conversion they want
if mode == 1:
inches = float(input("how many inches? "))
return print(inches * 2.54)
elif mode == 2:
cm = float(input("how many cm? "))
return print(cm / 2.54)
calc1 = Python_Calcalutor
print(calc1.number_multiplier(3,4))
print(calc1.number_remainder(20,7))
# calc1.cm_to_inches()
| true |
ff4fbd4b69001d74a64a11638e188d4434bb62df | Ramnirmal0/python | /palindrome using reveresed number.py | 456 | 4.25 | 4 | def reverse(num):
temp=num
rev=0
while(num>0):
rem=num%10
rev=(rev*10)+rem
num=num//10
print("/n Reversed Number is = ",rev)
check(temp,rev)
def check(num,rev):
if(num == rev):
print("The number is palindrome")
else:
print("The number is not palindrom")
num=int(input("Enter the number to be checked : "))
reverse(num)
| true |
e8279cccbd36f1566264f1ce71e3c31a9ed814d9 | johntelforduk/deep-racer | /cartesian_coordinates.py | 1,765 | 4.28125 | 4 | # Functions for manipulating cartesian coordinates expressed as [x, y] lists.
import math
def translation(vertex, delta):
"""Move, or slide, a coordinate in 2d space."""
[vertex_x, vertex_y] = vertex
[delta_x, delta_y] = delta
return [vertex_x + delta_x, vertex_y + delta_y]
def scale(vertex, scale_factor):
"""Move a coordinate closer / further from origin.
If done for all vertices in a 2d shape, it has the effect of changing the size of the whole shape."""
[vertex_x, vertex_y] = vertex
return [vertex_x * scale_factor, vertex_y * scale_factor]
def rotate_around_origin(vertex, rotation_degrees):
"""For parm coordinate and rotation in degrees, return its new coordinate after rotation."""
[vertex_x, vertex_y] = vertex
rotation_radians = math.radians(rotation_degrees)
# Method is described here,
# https://en.wikipedia.org/wiki/Rotation_of_axes#Derivation
return[vertex_x * math.cos(rotation_radians) + vertex_y * math.sin(rotation_radians),
- vertex_x * math.sin(rotation_radians) + vertex_y * math.cos(rotation_radians)
]
def rotate_around_a_point(vertex, pivot, rotation_degrees):
"""Rotate a parm coordinate around a parm pivot point by parm number of degrees."""
[pivot_x, pivot_y] = pivot
# Method has 3 steps,
# 1. Move the vertex so that centre of rotations is now the origin.
# 2. Rotate around origins.
# 3. Do the opposite of move in 1.
moved_vertex = translation(vertex, [-pivot_x, -pivot_y]) # Step 1.
rotated_vertex = rotate_around_origin(moved_vertex, rotation_degrees) # Step 2.
re_moved_vertex = translation(rotated_vertex, pivot) # Step 3.
return re_moved_vertex
| true |
6ca1156c74077f6e194cda11c8971988178d6967 | 31Sanskrati/Python | /letter.py | 273 | 4.40625 | 4 | letter = ''' Dear <|NAME|>,
You are selected!
<|DATE|> '''
your = input("Enter your name\n")
date = input("Enter date \n")
letter = letter.replace("<|NAME|>", your)
letter = letter.replace("<|DATE|>", date)
print(letter) | false |
aa3a94418e579c16e2f7261cb4af75827b0cb139 | alaanlimaa/Python_CVM1-2-3 | /Aula 10/ex028.py | 1,091 | 4.1875 | 4 | '''Exercício Python 28: Escreva um programa que faça o computador “pensar” em um
número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o
número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.'''
# PROGRAMA ABAIXO DESENVOLVIDO POR MIM'''
'''from random import randint
n = randint(0,5)
u = int(input('Qual foi o número escolhido pelo computador, de 0 à 5? : '))
if n == u:
print('Você acertou')
else:
print('Você errou')
print('O numero escolhido pelo computador foi {}'.format(n))'''
# RESOLVIDO PELO PROFESSOR
from random import randint
from time import sleep #SLEEP FAZ O COMPUTAR DORMIR/ESPERAR POR ALGUNS SEGUNDOS
cpu = randint(0, 5)
print('-=-' * 20)
print('Vou pensar em um número entre 0 e 5. Tente adivinhar...')
print('-=-' * 20)
gamer = int(input('Em qual número pensei? '))
print('PROCESSANDO...')
sleep(3) #COLOQUE ENTRE () O TEMPO QUE DESEJA
if gamer == cpu:
print('PARABÉNS! Você me venceu')
else:
print('GANHEI! Eu pensei no número {} e não no {}'.format(cpu, gamer))
| false |
d967dd15219ff0c45e87ab624706219ee703c73d | alaanlimaa/Python_CVM1-2-3 | /Aula 10/aula10.py | 896 | 4.21875 | 4 | # EXEMPLO 1 = TEMPO DE VIDA DO SEU CARRO
'''time =int(input('Quantos anos tem seu carro: '))
if time <=3:
print('Seu carro é zero bala ainda')
else:
print('Carro velho em')
print('=== FIM ===')'''
# USANDO CONDIÇÃO SIMPLIFICADA PARA REDUZIR O Nº DE LINHAS
'''time =int(input('Quantos anos tem seu carro ?'))
print('Carro novo' if time <=3 else 'Carro velho')
print(' == FIM == ')'''
# EXEMPLO 2
'''name = str(input('Qual é o seu nome? ')).strip().capitalize()
if name == 'Alan':
print('Que nome lindo brother')
else:
print('Não é tão bonito')
print('Bom dia, {}'.format(name))'''
# EXEMPLO 3
n1 = float(input('Qual a nota da primeira prova: '))
n2 = float(input('Qual a nota da segunda prona: '))
m = (n1 + n2)/2
print('Sua média foi {:.1f}'.format(m))
if m >= 5:
print('Você foi aprovado, parabéns')
else:
print('Você foi reprovado, tente novamente')
| false |
fe2c39e02fa723d98188615551b60cf0b5c8e7ae | chinmoy159/Python-Guide | /Algorithms/Sorting/merge_sort.py | 1,523 | 4.5625 | 5 | # Program in Python to demonstrate Merge Sorting algorithm
# Guide: https://www.geeksforgeeks.org/merge-sort/
#
# author: shubhojeet
# date: Oct 31, 2020: 2000 hrs
import random
def merge_sort(arr):
if len(arr) <= 1:
return
mid = len(arr) // 2
left_arr = []
right_arr = []
for it in range(0, mid):
left_arr.append(arr[it])
for it in range(mid, len(arr)):
right_arr.append(arr[it])
# Call merge sort on the first half
merge_sort(left_arr)
# Call merge sort on the second half
merge_sort(right_arr)
# Now, merging the sorted array
it_l = 0
it_r = 0
it = 0
while it_l < len(left_arr) and it_r < len(right_arr):
if left_arr[it_l] <= right_arr[it_r]:
arr[it] = left_arr[it_l]
it_l += 1
else:
arr[it] = right_arr[it_r]
it_r += 1
it += 1
while it_l < len(left_arr):
arr[it] = left_arr[it_l]
it += 1
it_l += 1
while it_r < len(right_arr):
arr[it] = right_arr[it_r]
it += 1
it_r += 1
if __name__ == '__main__':
arr = []
size_of_array = int(input("Enter the number of elements: "))
# Randomly generating numbers within the list: [0, 10007}
for it in range(0, size_of_array):
arr.append(random.randint(0, 1000000000007) % 10007)
print("\nArray before sorting: {0}".format(arr))
print("\n------------------------\n")
merge_sort(arr)
print("After Sorting: {0}".format(arr))
| false |
12406ed670cbd6fbceb212e80e297d56a67c2167 | chinmoy159/Python-Guide | /Algorithms/Sorting/selection_sort.py | 912 | 4.375 | 4 | # Program in Python to demonstrate Selection Sorting algorithm
# Guide: https://www.geeksforgeeks.org/selection-sort/
#
# author: shubhojeet
# date: Oct 31, 2020: 2000 hrs
import random
def selection_sort(arr):
size_of_array = len(arr)
for i in range(0, size_of_array - 1):
pos = i
for j in range(i + 1, size_of_array):
if arr[pos] > arr[j]:
pos = j
temp = arr[i]
arr[i] = arr[pos]
arr[pos] = temp
if __name__ == '__main__':
arr = []
size_of_array = int(input("Enter the number of elements: "))
# Randomly generating numbers within the list: [0, 10007}
for it in range(0, size_of_array):
arr.append(random.randint(0, 1000000000007) % 10007)
print("\nArray before sorting: {0}".format(arr))
print("\n------------------------\n")
selection_sort(arr)
print("After Sorting: {0}".format(arr))
| true |
dff052ce6e6e448eedfdbfad408cd3591fe78bb0 | beckahenryl/Data-Structures-and-Algorithms | /integerbubblesort.py | 459 | 4.28125 | 4 | '''
check if an array at one element is greater than
the element after it, then move it to check against
the next array. If the array is not, then keep it
the same
'''
array = [4,5,1,20,19,23,21,6,9]
def bubbleSort (array):
for i in range(len(array)):
for j in range(0, len(array)-i-1):
if array[j] > array[j+1]:
array[j], array[j+1]= array[j+1], array[j]
bubbleSort(array)
for i in range(len(array)):
print (array[i])
| true |
f4baff695988cb5240325a0dbfaac65da03a05e7 | soni653/cs-module-project-hash-tables | /applications/word_count/word_count.py | 555 | 4.125 | 4 | def word_count(s):
# Your code here
dict = {}
special_chars = '" : ; , . - + = / \ | [ ] { } ( ) * ^ &'.split()
s2 = ''.join(c.lower() for c in s if not c in special_chars)
for word in s2.split():
dict[word] = dict[word] + 1 if word in dict else 1
return dict
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.')) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.