blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
920d2ff4b74ff86352851e8435f0a9761c649392 | Cbkhare/Challenges | /multiply_list.py | 1,233 | 4.15625 | 4 | #In case data is passed as a parameter
from sys import argv
#from string import ascii_uppercase
file_name = argv[1]
fp = open(file_name,'r+')
contents = [ line.strip('\n').split('|') for line in fp]
#print (contents)
for item in contents:
part1 = list(item[0].split(' '))
part1.remove('')
part2 = list(item[1].split(' '))
part2.remove('')
stack = []
for i in range(len(part1)): #assumed length of both list are equal
stack.append(int(part1[i])*int(part2[i]))
print (str(stack).replace('[','').replace(']','').replace(', ',' '))
'''
Multiply Lists
Challenge Description:
You have 2 lists of positive integers. Write a program which multiplies corresponding elements in these lists.
Input sample:
Your program should accept as its first argument a path to a filename. Input example is the following
9 0 6 | 15 14 9
5 | 8
13 4 15 1 15 5 | 1 4 15 14 8 2
The lists are separated with a pipe char, numbers are separated with a space char.
The number of elements in lists are in range [1, 10].
The number of elements is the same in both lists.
Each element is a number in range [0, 99].
Output sample:
Print the result in the following way.
135 0 54
40
13 16 225 14 120 10
'''
| true |
0ea75af0aeb9c2bea86f5c8e95f9ca942344e8a9 | Cbkhare/Challenges | /HackerRank_Numpy_Transpose_Flatten.py | 1,424 | 4.125 | 4 | from sys import stdin as Si, maxsize as m
import numpy as np
class Solution:
pass
if __name__=='__main__':
n,m = map(int,Si.readline().split())
N = np.array([],int)
for i in range(n):
N = np.append(N,list(map(int,Si.readline().split())),axis=0)
N.shape = (n,m)
#Note:-
#To append vertically, Ex:- N = np.append(N,[[9],[10]],axis=1)
print(np.transpose(N))
print(N.flatten())
'''
Transpose
We can generate the transposition of an array using the tool numpy.transpose.
It will not affect the original array, but it will create a new array.
import numpy
my_array = numpy.array([[1,2,3],
[4,5,6]])
print numpy.transpose(my_array)
#Output
[[1 4]
[2 5]
[3 6]]
Flatten
The tool flatten creates a copy of the input array flattened to one dimension.
import numpy
my_array = numpy.array([[1,2,3],
[4,5,6]])
print my_array.flatten()
#Output
[1 2 3 4 5 6]
Task
You are given a NNXMM integer array matrix with space separated elements (NN = rows and MM = columns).
Your task is to print the transpose and flatten results.
Input Format
The first line contains the space separated values of NN and MM.
The next NN lines contains the space separated elements of MM columns.
Output Format
First, print the transpose array and then print the flatten.
Sample Input
2 2
1 2
3 4
Sample Output
[[1 3]
[2 4]]
[1 2 3 4]
'''
| true |
0c747667e925a98008c91f87dedbd34c2ab10e83 | Cbkhare/Challenges | /str_permutations.py | 1,087 | 4.3125 | 4 | #In case data is passed as a parameter
from sys import argv
from itertools import permutations
#from string import ascii_uppercase
file_name = argv[1]
fp = open(file_name,'r+')
contents = [line.strip('\n') for line in fp]
#print (contents)
for item in contents:
#print (item)
p_tups= sorted(permutations(item,len(item)))
stack = []
for tups in p_tups:
stack.append(''.join(tups))
print (','.join(stack))
'''
String Permutations
Sponsoring Company:
Challenge Description:
Write a program which prints all the permutations of a string in alphabetical order. We consider that digits < upper case letters < lower case letters. The sorting should be performed in ascending order.
Input sample:
Your program should accept a file as its first argument. The file contains input strings, one per line.
For example:
hat
abc
Zu6
Output sample:
Print to stdout the permutations of the string separated by comma, in alphabetical order.
For example:
aht,ath,hat,hta,tah,tha
abc,acb,bac,bca,cab,cba
6Zu,6uZ,Z6u,Zu6,u6Z,uZ6
'''
| true |
b6e142f9993d67e2eb0976dd1ddb304315cf28a6 | RaelViana/Python_3 | /ex018.py | 460 | 4.1875 | 4 | import math #importação da biblioteca math
"""
Aplicação do Módulo Math
"""
num = int(input('digite um número par a raiz Quadrada: ')) #recebe num do usuário
rq = math.sqrt(num) #aplica a função square root(raiz quadrada) em num
print('A raiz quadrada de {} é {}'.format(num, math.ceil(rq)))
# a função '.ceil' arredonda para cima um valor real
#--------------------------------------------------------------------------- | false |
ed7fccb8c5b758a7e8461d346a2637f4e380197a | RaelViana/Python_3 | /ex032.py | 613 | 4.25 | 4 |
"""
Estruturas condicionais simples e compostas.
"""
# estrutura simples
nome = str(input('Qual seu nome? '))
if nome == 'Maria': # execulta a ação caso valor seja igual
print('Que lindo nome..')
print('Bom dia "{}" !'.format(nome))
# estrutura composta
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
média = (nota1 + nota2) / 2
print('Sua média foi {:.1f}'.format(média))
if média >= 6:
print('Sua média foi boa Parabéns !! ')
else:
print('Sua média foi ruim ..Estude mais!!')
#############-- FIM --##############
| false |
ac2ffaa848aee4feacc96c124fa6ca0e6f4480e6 | PutkisDude/Developing-Python-Applications | /week3/3_2_nameDay.py | 490 | 4.25 | 4 | #Author Lauri Putkonen
#User enters a weekday number and the program tells the name of the day.
import calendar
day = int(input("Number of the day: ")) -1
print(calendar.day_name[day])
# Could also make a list and print from it but there is inbuilt module in python to do same thing
# weekdays = ["Monday", "Tuedsday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
# day = int(input("Number of the day ")) -1
# print(weekdays[day])
#OUTPUT EXAMLE:
#Number of the day: 3
#Wednesday
| true |
7a32efcdfaf7edef3e3ffaffabbeed9bed255bd3 | mkgmels73/Bertelsmann-Scholarship-Data-Track | /Python challenge/39_random_password.py | 1,389 | 4.40625 | 4 | #While generating a password by selecting random characters usually creates one that is relatively secure, it also generally gives a password that is difficult to memorize. As an alternative, some systems construct a password by taking two English words and concatenating them. While this password may not be as secure, it is normally much easier to memorize.Write a program that reads a file containing a list of words, randomly selects two of them, and concatenates them to produce a new password. When producing the password ensure that the total length is between 8 and 10 characters, and that each word used is at least three letters long. Capitalize each word in the password so that the user can easily see where one word ends and the next one begins. Finally, your program should display the password for the user.
#Run: 39_random_password.py names.txt
from sys import argv
import random
try:
name_file = argv[1]
lines = open(name_file).read().splitlines()
while 1:
# choosing 2 words
w1 = random.choice(lines)
w2 = random.choice(lines)
password = w1 + w2
# total length is between 8 and 10 characters, at least three letters by word
if(8 < len(password) < 10 and len(w1) >= 3 and len(w2) >= 3):
print('Password is:',w1.capitalize()+ w2.capitalize())
break
except:
print('Error in file')
| true |
12b45b29d942aec593b21161d8f6c4c6409722f2 | kimfucious/pythonic_algocasts | /solutions/matrix.py | 1,501 | 4.53125 | 5 | # --- Directions
# Write a function that accepts an integer, n, and returns a n x n spiral matrix.
# --- Examples
# matrix(2)
# [[1, 2],
# [4, 3]]
# matrix(3)
# [[1, 2, 3],
# [8, 9, 4],
# [7, 6, 5]]
# matrix(4)
# [[1, 2, 3, 4],
# [12, 13, 14, 5],
# [11, 16, 15, 6],
# [10, 9, 8, 7]]
def matrix(n):
"""
Need to create a list of n x n filled with None to avoid 'IndexError: list
index out of range' issues when using this technique Also note the +1s and
-1s on the ranges, as the second argument in a range is non-inclusive. There
are other ways to do this, but they make my head explode:
https://rosettacode.org/wiki/Spiral_matrix#Python
"""
spiral = [[None] * n for j in range(n)]
start_col, start_row = 0, 0
end_col, end_row = n-1, n-1
counter = 1
while start_col <= end_col and start_row <= end_row:
for index in range(start_row, end_col+1):
spiral[start_row][index] = counter
counter += 1
start_row += 1
for index in range(start_row, end_row+1):
spiral[index][end_col] = counter
counter += 1
end_col -= 1
for index in range(end_col, start_col-1, -1):
spiral[end_row][index] = counter
counter += 1
end_row -= 1
for index in range(end_row, start_row-1, -1):
spiral[index][start_col] = counter
counter += 1
start_col += 1
return spiral
| true |
dca708d0b43e4adea6e69b7ec9611e919310a472 | kimfucious/pythonic_algocasts | /exercises/reversestring.py | 273 | 4.375 | 4 | # --- Directions
# Given a string, return a new string with the reversed order of characters
# --- Examples
# reverse('apple') # returns 'leppa'
# reverse('hello') # returns 'olleh'
# reverse('Greetings!') # returns '!sgniteerG'
def reverse(string):
pass
| true |
b93be8d587df03aa1ef86361067b3ae45c42e861 | kimfucious/pythonic_algocasts | /solutions/levelwidth.py | 510 | 4.15625 | 4 | # --- Directions
# Given the root node of a tree, return a list where each element is the width
# of the tree at each level.
# --- Example
# Given:
# 0
# / | \
# 1 2 3
# | |
# 4 5
# Answer: [1, 3, 2]
def level_width(root):
widths = [0]
l = [root, "end"]
while len(l) > 1:
node = l.pop(0)
if node == "end":
l.append("end")
widths.append(0)
else:
l = l + node.children
widths[-1] += 1
return widths
| true |
fdc8646c69a3c4eb44cd016b4d1708ca77acef07 | kimfucious/pythonic_algocasts | /solutions/palindrome.py | 410 | 4.40625 | 4 | # --- Directions
# Given a string, return True if the string is a palindrome or False if it is
# not. Palindromes are strings that form the same word if it is reversed. *Do*
# include spaces and punctuation in determining if the string is a palindrome.
# --- Examples:
# palindrome("abba") # returns True
# palindrome("abcdefg") # returns False
def palindrome(string):
return string == string[::-1]
| true |
7484096aff7b568bf17f4bc683de3a538807ce52 | kimfucious/pythonic_algocasts | /solutions/capitalize.py | 1,010 | 4.4375 | 4 | # --- Directions
# Write a function that accepts a string. The function should capitalize the
# first letter of each word in the string then return the capitalized string.
# --- Examples
# capitalize('a short sentence') --> 'A Short Sentence'
# capitalize('a lazy fox') --> 'A Lazy Fox'
# capitalize('look, it is working!') --> 'Look, It Is Working!'
def capitalize(string):
"""
Using the Python str.title() method
"""
return string.title()
# def capitalize(string):
# """
# Using a loop on the string
# """
# result = string[0].upper()
# for index in range(1, len(string)):
# if string[index-1] == " ":
# result += string[index].upper()
# else:
# result += string[index]
# return result
# def capitalize(string):
# """
# Using a loop on a list split from the string
# """
# words = []
# for word in string.split(" "):
# words.append(word[0].upper() + word[1:])
# return " ".join(words)
| true |
6744b752c094cf71d347868859037e6256cdb4e8 | didomadresma/ebay_web_crawler | /ServiceTools/Switcher.py | 978 | 4.28125 | 4 | #!/usr/bin/env python3
__author__ = 'papermakkusu'
class Switch(object):
"""
Simple imitation of Switch case tool in Python. Used for visual simplification
"""
value = None
def __new__(class_, value):
"""
Assigns given value to class variable on class creation
:return: Returns True if the assignment was a success
:rtype: Boolean
"""
class_.value = value
return True
def case(*args):
"""
Matches given value with class value
Possible utilization:
#while Switch('b'):
# if case('a'):
# print("Sad face (T__T)")
# if case('b'):
# print("Eurica!")
#>>> Eurica!
:return: returns True if given argument is in .value field of Switch class
:rtype: Boolean
Doctest:
>>> swi = Switch('Caramba!')
>>> case('Pirates!')
False
>>> case('Caramba!')
True
"""
return any(arg == Switch.value for arg in args)
| true |
21aa97d8eab6bb0f41c63d799ddb126be72a467f | Pooja5573/DS-Pragms | /table_fib_fact.py | 867 | 4.25 | 4 | #ASSIGNMENT : 1
#to find factorial of given num
n = int(input("enter the num"))
fact = 1
while n>=2 :
fact = fact*n
n-=1
print("factorial : ",fact)
##ASSIGNMENT : 2
#to find the fibonacci series
n = int(input("enter the num"))
a = 0
b = 1
c = a+b
while c <= n:
print("THE FIBONACCI series : ",c)
a=b
b=c
c = a+b
#ASSIGNMENT : 3
#to find marks, avg, tot of 5 - students
i = 1
while i <= 5:
a = input("enter name and five subjects marks:")
b = a.split()
print(b)
print("student name:", b[0])
j = 1
sum = 0
while j<=5 :
print(int(b[j]))
sum = sum + int(b[j])
j = j+1
print("sum:", sum)
avg = sum/5
print("avg : ",avg)
print("A+" if avg>=90 else "A" if avg<90 and avg>=80 else ("B" if avg<80 and avg>=70 else "C"))
i = i+1
| false |
e7d5d7e1c7a2d766c49de8e0009482ad488a3a63 | Priktopic/python-dsa | /str_manipualtion/replace_string_"FOO"_"OOF".py | 1,052 | 4.3125 | 4 | """
If a string has "FOO", it will get replaced with "OOF". However, this might create new instances of "FOO". Write a program that goes through a string as many times
as required to replace each instances of "FOO" with "OOF". Eg - In "FOOOOOOPLE", 1st time it will become "OOFOOOOPLE". Again we have "FOO", so the 2nd iteration it
will become "OOOOFOOPLE". In the next iteration it will become "OOOOOOFPLE" since we have another "FOO".
"""
def string_manipulation(new_string, available_string, replace_string_with):
s1=""
for i in new_string:
s1 += i # stores each chracter "i" in new string "s1"
if available_string in s1: # checks if s1 contains "FOO"
s1 = s1.replace(available_string,replace_string_with) # if condition satisfies, it replaces "FOO" with "OOF" and stores it in same "s1".
# In the next iteration it adds, the new character "i" of "new_string" with "s1" that already contains replaced string.
return s1
OUTPUT = string_manipulation ("FOOOOOOOPLE", "FOO", "OOF")
print(OUTPUT)
| true |
57899dbcf24323514b453e3b1a9de5bc01379c8c | Priktopic/python-dsa | /linkedlist/largest_sum_of_ele.py | 1,149 | 4.4375 | 4 | '''
You have been given an array containg numbers. Find and return the largest sum in a contiguous subarray within the input array.
Example 1:
arr= [1, 2, 3, -4, 6]
The largest sum is 8, which is the sum of all elements of the array.
Example 2:
arr = [1, 2, -5, -4, 1, 6]
The largest sum is 7, which is the sum of the last two elements of the array.
'''
def max_sum_subarray(arr):
current_sum = arr[0] # `current_sum` denotes the sum of a subarray
max_sum = arr[0] # `max_sum` denotes the maximum value of `current_sum` ever
# Loop from VALUE at index position 1 till the end of the array
for element in arr[1:]:
'''
# Compare (current_sum + element) vs (element)
# If (current_sum + element) is higher, it denotes the addition of the element to the current subarray
# If (element) alone is higher, it denotes the starting of a new subarray
'''
current_sum = max(current_sum + element, element)
# Update (overwrite) `max_sum`, if it is lower than the updated `current_sum`
max_sum = max(current_sum, max_sum)
return max_sum
| true |
17e30a414fdf6bf310fa229ddede6b7dd23551bc | Priktopic/python-dsa | /str_manipualtion/rmv_digits_replace_others_with_#.py | 350 | 4.25 | 4 | """
consider a string that will have digits in that, we need to remove all the not digits and replace the digits with #
"""
def replace_digits(s):
s1 = ""
for i in s:
if i.isdigit():
s1 += i
return(re.sub('[0-9]','#',s1)) # modified string which is after replacing the # with digits
replace_digits("#2a$#b%c%561#")
| true |
153687f5a58296d127d14789c96ce8843eb236a0 | dylanly/Python-Practice | /best_friends.py | 386 | 4.25 | 4 | list_friends = ['Ken', 'Mikey', 'Mitchell', 'Micow']
print("Below you can see all my best friends!\n")
for friend in list_friends:
print(friend)
if 'Drew' not in list_friends:
print("\n:O \nDrew is not in my friends list!!\n")
list_friends.append('Drew')
for friend in list_friends:
print(friend)
print("\nI fixed my best friend's list hehe xD")
| true |
41a3c87f4494962b830a3fae87ce7864d7b2a502 | CHINNACHARYDev/PythonBasics | /venv/ConditionalStatements.py | 1,071 | 4.5 | 4 | # Conditional statements (Selection Statements/Decesion Making Statements)
# It will decide the execution of a block of code based on the condition of the expression
# 'if' Statement
# 'if else' Statement
# 'if elif else' Statement
# Nested 'if' Statement
A = 'CHINNA'
B = 'CHARY'
C = 'CHINNACHARY'
D = 'CHINNA CHARY'
# If Statement: It executes the set of instructions based on the condition
if A + B == C:
print('If Statement IF', C)
# If Else Statement: It executes the set of instructions based on the condition
if A + B == C:
print('If Else Statement IF', C)
else:
print('If Else Statement ELSE', A + B)
# If ElIf Else Statement:
if A + B == D:
print('If ElIf Else Statement IF', D)
elif A + B == C:
print('If ElIf Else Statement ELIF', C)
else:
print('If ElIf Else Statement ELSE', A + B)
# Nested If Statement:
if A + B == D:
print('Nested If Statement IF1', D)
if A + B == C:
print('Nested If Statement IF2', C)
else:
print('Nested If Statement ELSE1', C)
else:
print('Nested If Statement ELSE2', A + B) | false |
7014390c7d7031113d04ac773ee1dec33950aeea | KKobuszewski/pwzn | /tasks/zaj2/zadanie1.py | 1,623 | 4.15625 | 4 | # -*- coding: utf-8 -*-
def xrange(start=0, stop=None, step=None):
"""
Funkcja która działa jak funkcja range (wbudowana i z poprzednich zajęć)
która działa dla liczb całkowitych.
"""
#print(args,stop,step)
x = start
if step is None:
step = 1
if stop is None:
stop = start
x = 0
while x < stop:
yield x
x = x + step
#print(list(xrange(2,15,2)))#przez print nie tworzy sie referencja;
print(list(xrange(5)))
"""
range(n) creates a list containing all the integers 0..n-1.
This is a problem if you do range(1000000), because you'll end up with a >4Mb list.
xrange deals with this by returning an object that pretends to be a list,
but just works out the number needed from the index asked for, and returns that.
For performance, especially when you're iterating over a large range, xrange() is usually better.
However, there are still a few cases why you might prefer range():
In python 3, range() does what xrange() used to do and xrange() does not exist.
If you want to write code that will run on both Python 2 and Python 3, you can't use xrange().
range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times.
xrange() has to reconstruct the integer object every time, but range() will have real integer objects.
(It will always perform worse in terms of memory however)
xrange() isn't usable in all cases where a real list is needed.
For instance, it doesn't support slices, or any list methods.
""" | true |
9aab8e7e48f9e49f5769bd101b6697adb7809ea5 | clark-ethan9595/CS108 | /lab02/stick_figure.py | 936 | 4.1875 | 4 | ''' Drawing Stick Figure
September 11, 2014
Lab 02
@author Serita Nelesen (smn4)
@authors Ethan and Mollie (elc3 and mfh6)
'''
#Gain access to the collection of code named "turtle"
import turtle
#Give the name "window" to the screen where the turtle will appear
window = turtle.Screen()
#Create a turtle and name it bob
bob = turtle.Turtle()
#Gain access to the math library
import math
#Make UNIT equal to 50 pixels
UNIT = 50
#Make a refer to the Pythagorean theorem.
a = math.sqrt(pow(UNIT, 2) + pow(UNIT,2))
#Draw a stick figure guy
bob.pensize(3)
bob.forward(UNIT*2)
bob.penup()
bob.left(90)
bob.forward(UNIT*3)
bob.left(90)
bob.forward(UNIT)
bob.pendown()
bob.circle(UNIT)
bob.penup()
bob.left(90)
bob.forward(UNIT*2)
bob.pendown()
bob.forward(UNIT*2)
bob.right(45)
bob.forward(a)
bob.penup()
bob.left(135)
bob.forward(UNIT*2)
bob.pendown()
bob.left(135)
bob.forward(a)
#Keep the window open until it is clicked
window.exitonclick() | false |
91023ff23cf97b09c25c2fe53f787aa764c8ca69 | clark-ethan9595/CS108 | /lab05/song.py | 1,076 | 4.375 | 4 | ''' A program to specify verses, container, and desired food/beverage.
Fall 2014
Lab 05
@author Ethan Clark (elc3)
'''
#Prompt user for their own version of the song lyrics
verses = int(input('Please give number of verses for song:'))
container = input('Please give a container for your food/beverage:')
substance = input('Please give a desired food/beverage:')
#Fix the number of verses to a variable to use in the last verse of the song.
number = verses
#Use a loop to write the song with the user-desired verses, container, and substance.
for count in range(verses, -1, -1):
if verses != 0:
print(verses, container + '(s) of', substance, 'on the wall,', verses, container + '(s) of', substance + '. Take one down, pass it around,', (verses - 1), container + '(s) of', substance, 'on the wall.')
verses = verses - 1
else:
print(verses, container + '(s) of', substance, 'on the wall,', verses, container + '(s) of', substance + '. Go to the store and buy some more.', number, container + '(s) of', substance, 'on the wall.')
print('Finish') | true |
8bcb5e719f1148779689d7d80422c468257a9f0f | clark-ethan9595/CS108 | /lab02/einstein.py | 729 | 4.21875 | 4 | ''' Variables and Expessions
September 11, 2014
Lab 02
@author Ethan and Mollie (elc3 and mfh6)
'''
#Ask user for a three digit number.
number = int(input('Give a three digit number where the first and last digits are more than 2 apart : '))
#Get the reverse of the user entered number.
rev_number = (number//1)%10 * 100 + (number//10)%10 * 10 + (number//100)%10
#Find the difference of the number and the reverse of the number.
difference = abs(number - rev_number)
#Find the reverse of the difference.
rev_difference = (difference//1)%10 * 100 + (difference//10)%10 * 10 + (difference//100)%10
#Print the difference of the difference and the reverse of the difference.
print(difference + rev_difference)
print(rev_number)
| true |
2ab3022ae0ea51d58964fffd5887dbd5f1812974 | huajianmao/pyleet | /solutions/a0056mergeintervals.py | 1,085 | 4.21875 | 4 | # -*- coding: utf-8 -*-
################################################
#
# URL:
# =====
# https://leetcode.com/problems/merge-intervals/
#
# DESC:
# =====
# Given a collection of intervals, merge all overlapping intervals.
#
# Example 1:
# Input: [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
#
# Example 2:
# Input: [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] and [4,5] are considered overlapping.
#
################################################
from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
else:
result = []
intervals.sort(key=lambda x: x[0])
current = intervals[0]
for interval in intervals:
if interval[0] <= current[1]:
current = [current[0], max(interval[1], current[1])]
else:
result.append(current)
current = interval
result.append(current)
return result
| true |
cd72d43f6a973cf8d0bb3b522e9226dc7f8eef76 | ACES-DYPCOE/Data-Structure | /Searching and Sorting/Python/merge_sort.py | 1,939 | 4.125 | 4 | ''' Merge Sort is a Divide and Conquer algorithm. It divides input
array in two halves, calls itself for the two halves and then merges the
two sorted halves.The merge() function is used for merging two halves.
The merge(arr, l, m, r) is key process that assumes that arr[l..m] and
arr[m+1..r] are sorted and merges the two sorted sub-arrays into one'''
'''////ALGORITHM////
#MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)'''
'''Python program for implementation of MergeSort'''
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2 # Finding the mid of the array
left = arr[:mid] # Dividing the array elements
right = arr[mid:] # into 2 halves
mergeSort(left) # Sorting the first half
mergeSort(right) # Sorting the second half
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# Checking if any element was left
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
# printing the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
arr = [12, 11, 13, 5, 6, 7]
print("Given array is: ")
printList(arr)
mergeSort(arr)
print("Sorted array is: ")
printList(arr)
| true |
aad803d232b8bb4e205cd3b0cac8233f228b44d3 | ACES-DYPCOE/Data-Structure | /Searching and Sorting/Python/shell_sort.py | 1,254 | 4.15625 | 4 | #Shell sort algorithm using python
#Shell sort algorithm is an improved form of insertion sort algorithm as it compares elements separated by a gap of several position.
#In Shell sort algorithm, the elements in an array are sorted in multiple passes and in each pass, data are taken with smaller and smaller gap sizes.
# However, the finale of shell sort algorithm is a plain insertion sort algorithm.
def shellsort(a): #initialize the function definition
gap=len(a)//2 #Return the number of items in a container
while gap>0:
for i in range(gap,len(a)):
j=a[i] ##initialize j to a[i]
pos=i #initialize pos to i
while pos>=gap and j<a[pos-gap]: #inner while loop
a[pos]=a[pos-gap]
pos=pos-gap
a[pos]=j
gap=gap//2
n=int(input("Enter length of array: "))
print("Enter values in array: ") #taking input from user
arr=[int(input()) for i in range(n)]
shellsort(arr) #calling of function definition
print("sorted array: ",arr)
#Time complexity : O(n*log n)
#space complexity : O(1)
| true |
4fc35071689bad45b1cc4c9c02aee401b1364ccc | shiuchunming/python3_learning | /datatype.py | 1,496 | 4.1875 | 4 |
def list():
print("---List---")
a_list = ['a']
a_list = a_list + [2.0, 3]
a_list.append([1, 2])
a_list.extend(['four', '#'])
a_list.insert(0, '1')
print("List A: " + str(a_list))
print("Length of list: " + str(len(a_list)))
print("Slice List:" + str(a_list[1:3]))
print("Slice List: " + str(a_list[3:]))
b_list = a_list
a_list.append(False)
print("Copy by reference: " + str(a_list))
print("Copy by reference: " + str(b_list))
b_list = a_list[:]
a_list.append("ABC")
print("Copy by value: " + str(a_list))
print("Copy by value: " + str(b_list))
def tuple():
print("\n---Tuple---")
a_tuple = ("a", "b", "mpilgrim", "z", "example")
print("Tuple A: " + str(a_tuple))
try:
a_tuple.append(False)
except AttributeError:
print("Can't Append; Tuple is a immutable version of list")
print(type((False)))
print(type((False,)))
def set():
print("\n---Set---")
a_set = {1, 2}
a_set.add(3)
print("Set A: " + str(a_set))
a_set.update({1, 2, 3, 4})
a_set.update([1, 2, 3, 0])
print("Set A: " + str(a_set))
a_set.discard(10)
try:
a_set.remove(10)
except:
print("Element 10 does not exists in Set")
def dictionary():
print("\n---dictionary---")
a_dict = {'server': 'db.diveintopython3.org', 'database': 'oracle'}
print(a_dict['server'])
if __name__ == '__main__':
list()
tuple()
set()
dictionary() | false |
f5cf5e85ffd22f6a59d4d1c1f183b2b668f82e29 | faizanzafar40/Intro-to-Programming-in-Python | /2. Practice Programs/6. if_statement.py | 298 | 4.1875 | 4 | """
here I am
using 'if' statement to make decisions based
on user age
"""
age = int(input("Enter your age:"))
if(age >= 18):
print("You can watch R-Rated movies!")
elif(age > 13 and age <= 17):
print("You can watch PG-13 movies!")
else:
print("You should only watch Cartoon Network") | true |
c56354bd9e49655c5f7f4a4c8f009ee7c13b7272 | razi-rais/toy-crypto | /rsa.py | 1,457 | 4.1875 | 4 | # Toy RSA algo
from rsaKeyGen import gen_keypair
# Pick two primes, i.e. 13, 7. Try substituting different small primes
prime1 = 13
prime2 = 7
# Their product is your modulus number
modulus = prime1 * prime2
print "Take prime numbers %d, %d make composite number to use as modulus: %d" % (prime1, prime2, modulus)
print "RSA security depends on the difficulty of determining the prime factors of a composite number."
# Key generation is the most complicated part of RSA. See rsaKeyGen.py for algorithms
print "\n*~*~*~ Key Generation *~*~*~"
keys = gen_keypair(prime1, prime2)
print "All possible keys:", keys
# We'll go with the first keypair: pub 5, priv 29
pubkey = keys[0]['pub']
privkey = keys[0]['priv']
print "\nYour pubkey is %d, your privkey is %d\n" % (pubkey, privkey)
def encrypt_char(num):
# multiply num by itself, pubkey times
r = num ** pubkey
return r % modulus
def decrypt_char(num):
# multiply encrypted num by itself, modulus times
r = num ** privkey
return r % modulus
def encrypt_word(word):
encwd = ''
for char in word:
n = ord(char)
enc = encrypt_char(n)
encwd += chr(enc)
return encwd
def decrypt_word(word):
decwd = ''
for char in word:
n = ord(char)
dec = decrypt_char(n)
decwd += chr(dec)
return decwd
encwd = encrypt_word('CLOUD')
print "Encrypted word: ", encwd
decwd = decrypt_word(encwd)
print "Decrypted word: ", decwd
| true |
26960cd52e3c63adcedc75d86f102741dea7aace | nitishjatwar21/Competitive-Coding-Repository | /Bit Manupulation/Is Power Of 2/is_pow_of_2.py | 238 | 4.4375 | 4 | def is_pow_of_2(num):
return (num and (not(num & (num-1))))
number = 5
if(is_pow_of_2(number)):
print("number is power of 2 ")
else:
print("number is not a power of 2")
'''
Input : 5
Output :number is not a power of 2
'''
| false |
2d727e0acb9fcca8ecee72742970dbc8831af33d | RodolfoBaez/financial-calculators | /main.py | 1,662 | 4.21875 | 4 |
print("Welcome to Financial-Calculators ")
print("What would you like to calulate ")
print("")
print("1. Bank Savings Account Interest ")
print("2. Stock Market Growth Per Year")
print("")
user_choice = input("Input your response ")
if user_choice == "1":
print("Using the Annual Inflation Rate Of 2.5%, We Will Tell You If Your Beating Inflation")
initial_deposit = float(input("Ammount Of Initial Deposit "))
time_for_interest = float(input("How long Are You Going To Save For In (Years) "))
APY = float(input("What Is Your APY For Your Savings Account "))
ammount_of_interest = initial_deposit * ((1 + APY/100) ** time_for_interest) - initial_deposit
print("")
print("Your Ending Balance In Your Savings Account After " + str(time_for_interest) + " Years Is ")
print(ammount_of_interest + initial_deposit)
print("")
print("You Earned In Interest " + "$" + str(ammount_of_interest))
print("")
if 2.50 > APY:
print("Inflation Beat Your Saving Account Interest, Try To Beat The Inflation Rate Of 2.50% With A Better Savings Account ")
if 2.50 < APY:
print("You Beat inflation With Your Saving Account Interest, Great Saving Account You Have ")
elif user_choice == "2":
print("Using The Annual Returns of the Stock Market Of 10%, We Will Calulate You Investment Gains")
initial_investment = float(input("How Much Are You Investing In the Stock Market "))
time = float(input("For How Long Are you Planning To Invest For (Years) "))
ammount_of_investment = initial_investment * ((1 + 10/100) ** time) - initial_investment
print("You gained " + "$" + str(ammount_of_investment))
else:
print("invaild responds")
| false |
7715a9ad5a59aa0962b4257520b0143b0b9e98ea | sirdesmond09/mypython- | /pro.py | 2,901 | 4.125 | 4 | print("WELCOME TO MATHCALS")
operations=['Add', 'Sub', 'Mult', 'Divi']
print(operations)
g=1
q=int(input("Choose the number of times you want to solve "))
while g<=q:
gee=input("choose your arthimetric operation")
if (gee==operations[0]):
w=int(input("are you adding 2 or 3 numbers"))
if (w==2):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
def sum2(p,r):
ans=(p+r)
return ans
print(sum2(a,b))
elif(w==3):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
c=int(input("enter third number"))
def sum3(x,y,z):
ans=(x+y+z)
return ans
print(sum3(a,b,c))
else:
print("wrong input")
elif (gee==operations[1]):
t=int(input("are you subtracting 2 or 3 numbers"))
if (t==2):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
def sub2(p,r):
minus=(p-r)
return minus
print(sub2(a,b))
elif(t==3):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
c=int(input("enter third number"))
def sub3(x,y,z):
minus=(x-y-z)
return minus
print(sub3(a,b,c))
else:
print("wrong input")
elif (gee==operations[2]):
l=int(input("are you multiplying 2 or 3 numbers"))
if (l==2):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
def pro2(p,r):
multiply=(p*r)
return multiply
print(pro2(a,b))
elif(l==3):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
c=int(input("enter third number"))
def pro3(x,y,z):
multiply=(x*y*z)
return multiply
print(pro3(a,b,c))
else:
print("wrong input")
elif (gee==operations[2]):
h=int(input("are you dividing 2 or 3 numbers"))
if (h==2):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
def quo2(p,r):
divide=(p/r)
return divide
print(quo2(a,b))
elif(h==3):
a=int(input("enter first number:"))
b=int(input("enter second number:"))
c=int(input("enter third number"))
def quo3(x,y,z):
divide=(x/y/z)
return divide
print(quo3(a,b,c))
else:
print("wrong input")
else:
print("Invalid input")
g=g+1
print("Thanks for running my code")
| false |
5a25d397ed98da278f080f2d97fd9149c33e403e | FranHuzon/ASIR | /Marcas/Python/Ejercicios/Listas/Ejercicio 2.py | 2,246 | 4.3125 | 4 | #-------------------- CREACIÓN LISTA --------------------#
palabras = input('Escribe la palabra que quieras añadir a la lista (Para terminar pulsa ENTER sin escribir nada): ')
lista_palabras = []
while palabras != '':
lista_palabras.append(palabras)
palabras = input('Escribe la palabra que quieras añadir a la lista (Para terminar pulsa ENTER sin escribir nada): ')
#-------------------- FIN CREACIÓN LISTA --------------------#
print ()
#-------------------- MENU --------------------#
print ('1. Contar.')
print ('2. Modificar.')
print ('3. Eliminar.')
print ('4. Salir.')
opcion = int(input('Elige una opción: '))
while opcion != 4:
#-------------------- DESARROLLO MENU --------------------#
#-------------------- DESARROLLO MENU: BUSCAR --------------------#
if opcion == 1:
palabra_buscar = input('¿Que palabra quiere buscar?: ')
print ('La palabra {0} aparece {1} veces en la lista.'.format(palabra_buscar,lista_palabras.count(palabra_buscar)))
#-------------------- FIN DESARROLLO MENU: BUSCAR --------------------#
#-------------------- DESARROLLO MENU: MODIFICAR --------------------#
elif opcion == 2:
indice = 0
palabra_sustituir = input('¿Que palabra quiere sustituir?: ')
palabra_sustituta = input('¿Que palabra va a sustituir a la palabra {0}?: '.format(palabra_sustituir))
for elem in lista_palabras:
if elem == palabra_sustituir:
lista_palabras[indice] = palabra_sustituta
indice += 1
print ('Lista actual {0}'.format(lista_palabras))
#-------------------- FIN DESARROLLO MENU: MODIFICAR --------------------#
#-------------------- DESARROLLO MENU: ELIMINAR --------------------#
elif opcion == 3:
palabra_eliminar = input('¿Que palabra quiere eliminar de la lista?: ')
for elem in lista_palabras:
if elem == palabra_eliminar:
lista_palabras.remove(palabra_eliminar)
print ('Lista actual {0}'.format(lista_palabras))
#-------------------- FIN DESARROLLO MENU: ELIMINAR --------------------#
else:
print ('Adios!!!!')
#-------------------- FIN DESARROLLO MENU --------------------#
print ('1. Contar.')
print ('2. Modificar.')
print ('3. Eliminar.')
print ('4. Salir.')
opcion = int(input('Elige una opción: '))
#-------------------- FIN MENU --------------------# | false |
bc60a2c690b7f7e51f086f92258a7e9bc14ff466 | raoliver/Self-Taught-Python | /Part II/Chapter 14.py | 997 | 4.21875 | 4 | ##More OOP
class Rectangle():
recs = []#class variable
def __init__(self, w, l):
self.width = w#Instance variable
self.len = l
self.recs.append((self.width, self.len))#Appends the object to the list recs
def print_size(self):
print("""{} by {}""".format(self.width, self.len))
r1 = Rectangle(10, 24)
r2 = Rectangle(20, 40)
r3 = Rectangle(100, 200)
print(Rectangle.recs)
##Magic Methods
class Lion:
def __init__(self, name):
self.name = name
#Overrides inherited __repr__ method and prints name
def __repr__(self):
return self.name
lion = Lion('Dilbert')
print(lion)
#Another Magic Method Example
class AlwaysPositive:
def __init__(self, number) :
self.n = number
##overrides the add function to return the absolute value of 2 numbers added together
def __add__(self, other):
return abs(self.n +
other.n)
x = AlwaysPositive(-20)
y = AlwaysPositive(10)
print(x + y)
| true |
7633a1fedf0957e1577ffcae5d1b35fc894a3b34 | knmarvel/backend-katas-functions-loops | /main.py | 2,253 | 4.25 | 4 | #!/usr/bin/env python
import sys
import math
"""Implements math functions without using operators except for '+' and '-' """
__author__ = "github.com/knmavel"
def add(x, y):
added = x + y
return added
def multiply(x, y):
multiplied = 0
if x >= 0 and y >= 0:
for counter in range(y):
multiplied = add(multiplied, x)
return multiplied
if x <= 0 and y <= 0:
for counter in range(-y):
multiplied = add(multiplied, -x)
return multiplied
if x < 0 and y >= 0:
for counter in range(y):
multiplied = add(multiplied, x)
return multiplied
if x >= 0 and y < 0:
for counter in range(x):
multiplied = add(multiplied, y)
return multiplied
def power(x, n):
print(x**n)
powered = 1
for counter in range(n):
powered = multiply(powered, x)
return powered
def factorial(x):
if x == 0:
return 1
for counter in range(x-1, 0, -1):
x = multiply(x, counter)
return x
def fibonacci(n):
fib = [0, 1]
for index in range(0, n):
fib.append(fib[index]+fib[index+1])
return fib[n]
def main():
if len(sys.argv) < 3:
print ('usage: python main.py {--add | --multiply | --power | --factorial | fibonacci } {[x ,y] | [x, y] | [x, n] | [x] | [n] ')
sys.exit(1)
if sys.argv[0] == "--add" or sys.argv[0] == "--multiply" or sys.argv[0] == "--power":
if len(sys.argv) != 5:
print("need two integer arguments for that function")
else:
if len(sys.argv) != 4:
print("need one integer parameter for that function")
option = sys.argv[1]
numbers = sys.argv[2:]
if option == '--add':
print(add(int(numbers[0]), int(numbers[1])))
elif option == '--multiply':
print(multiply(int(numbers[0]), int(numbers[1])))
elif option == '--power':
print(power(int(numbers[0]), int(numbers[1])))
elif option == '--factorial':
print(factorial(int(numbers[0])))
elif option == '--fibonacci':
print(fibonacci(int(numbers[0])))
else:
print ('unknown option: ' + option)
sys.exit(1)
if __name__ == '__main__':
main()
| true |
e2755d36a518efc21f5c479c4c3f32a54408eade | behind-the-data/ccp | /chap2/name.py | 534 | 4.3125 | 4 | name = "ada lovelace"
print(name.title()) # the title() method returns titlecased STRING.
# All below are optional
# Only Capital letters
print(name.upper())
# Only Lower letters
print(name.lower())
## Concatenation ##
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
## Pass a string variable within a string ##
print("Hello, " + full_name.title() + "!")
## Store the above in a varialbe, then print said variable ##
message = "Hello, " + full_name.title() + "!"
print(message)
| true |
2d29f47c7b91c33feac52f38bf0168ac6918d821 | jcol27/project-euler | /41.py | 1,674 | 4.3125 | 4 | import math
import itertools
'''
We shall say that an n-digit number is pandigital if it makes
use of all the digits 1 to n exactly once. For example, 2143
is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
Can use itertools similar to previous problem. We can use the
rule than a number is divisible by three if and only if the
sum of the digits of the number is divisible by three to see
that for pandigital numbers, only those with 4 or 7 digits can
be prime.
'''
'''
Function to find if a number is prime, simply
checks if a number is divisible by values other
than one and itself.
'''
def is_prime(num):
if (num == 0 or num == 1):
return 0
for i in range(2, math.floor(num/2) + 1):
if (num % i == 0):
return False
return True
# Create initial iterable and variables
num = 0
count = 1
best = 0
# Since we only care about the largest, start at largest possible
# and stop at first solution
while best == 0:
# Iterable for 7 digit pandigital numbers
iterables = itertools.permutations(list(range(7,0,-1)),7)
for num in iterables:
num = int("".join(str(s) for s in num))
# Check if prime
if (is_prime(num) and num > best):
best = num
break
# Iterable for 4 digit pandigital numbers
if best != 0:
iterables = itertools.permutations(list(range(4,0,-1)),4)
for num in iterables:
num = int("".join(str(s) for s in num))
# Check if prime
if (is_prime(num) and num > best):
best = num
break
print(f"Solution = {best}") | true |
5c4fc548e88cada634ce1e2c84bf0fa494d6b6a8 | mparkash22/learning | /pythonfordatascience/raise.py | 538 | 4.1875 | 4 | #raise the value1 to value2
def raise_both(value1, value2): #function header
"""Raise value1 to the power of value 2 and vice versa""" #docstring
new_value1= value1 ** value2 #function body
new_value2= value2 ** value1
new_tuple = (new_value1, new_value2)
return new_tuple
#we can print the tuple value using index
powr = raise_both(2,5) #function call
print(powr[0])
print(powr[1])
#we can unpack the tuple and print the value
power1,power2 = raise_both(2,5)
print(power1)
print(power2) | true |
f9dbc54c6b2cf46b0f879bce94908ff944045eb2 | leemyoungwoo/pybasic | /python/활용자료/예제/04/ex4-4.py | 218 | 4.1875 | 4 | for i in range(10) :
print(i, end =' ')
print()
for i in range(1, 11) :
print(i, end =' ')
print()
for i in range(1, 10, 2) :
print(i, end =' ')
print()
for i in range(20, 0, -2) :
print(i, end =' ') | false |
856ea8f0efef73fba334f00caa090b9a2697c0a8 | xiaomengxiangjia/Python | /foods.py | 580 | 4.34375 | 4 | my_foods = ['pizza', 'falafel', 'carrot cake', 'beer', 'chicken']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('icecream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friends's favorite foods are:")
print(friend_foods)
print("The first three items in the list are:" )
print(my_foods[:3])
print("The items from the middle of the list are:" )
print(my_foods[1:4])
print("The last three items in the list are:" )
print(my_foods[-3:])
for my_food in my_foods:
print(my_food)
for friend_food in friend_foods:
print(friend_food)
| false |
aec15d1708777d5cccc103aa309fab48491fb53c | jesuarezt/datacamp_learning | /python_career_machine_learning_scientist/04_tree_based_models_in_python/classification_and_regression_tree/02_entropy.py | 1,607 | 4.125 | 4 | #Using entropy as a criterion
#
#In this exercise, you'll train a classification tree on the Wisconsin Breast Cancer dataset using entropy as an information criterion. #You'll do so using all the 30 features in the dataset, which is split into 80% train and 20% test.
##
##X_train as well as the array of labels y_train are available in your workspace.
# Import DecisionTreeClassifier from sklearn.tree
from sklearn.tree import DecisionTreeClassifier
# Instantiate dt_entropy, set 'entropy' as the information criterion
dt_entropy = DecisionTreeClassifier(max_depth=8, criterion='entropy', random_state=1)
# Fit dt_entropy to the training set
dt_entropy.fit(X_train, y_train)
#Entropy vs Gini index
#
#In this exercise you'll compare the test set accuracy of dt_entropy to the accuracy of another tree named dt_gini. The tree dt_gini was trained on the same dataset using the same parameters except for the information criterion which was set to the gini index using the keyword 'gini'.
#
#X_test, y_test, dt_entropy, as well as accuracy_gini which corresponds to the test set accuracy achieved by dt_gini are available in your workspace.
# Import accuracy_score from sklearn.metrics
from sklearn.metrics import accuracy_score
# Use dt_entropy to predict test set labels
y_pred= dt_entropy.predict(X_test)
# Evaluate accuracy_entropy
accuracy_entropy = accuracy_score(y_pred, y_test)
# Print accuracy_entropy
print('Accuracy achieved by using entropy: ', accuracy_entropy)
# Print accuracy_gini
print('Accuracy achieved by using the gini index: ', accuracy_gini) | true |
a5b6035fb3d38ef3459cfd842e230bbfb2148583 | jesuarezt/datacamp_learning | /python_career_machine_learning_scientist/06_clustering_analysis_in_python/03_kmeans_clustering/01_example_kmeans.py | 1,881 | 4.1875 | 4 | #K-means clustering: first exercise
#
#This exercise will familiarize you with the usage of k-means clustering on a dataset. Let us use the Comic Con dataset and check how k-means clustering works on it.
#
#Recall the two steps of k-means clustering:
#
# Define cluster centers through kmeans() function. It has two required arguments: observations and number of clusters.
# Assign cluster labels through the vq() function. It has two required arguments: observations and cluster centers.
#
#The data is stored in a Pandas data frame, comic_con. x_scaled and y_scaled are the column names of the standardized X and Y coordinates of people at a given point in time.
# Import the kmeans and vq functions
from scipy.cluster.vq import kmeans, vq
# Generate cluster centers
cluster_centers, distortion = kmeans(comic_con[['x_scaled', 'y_scaled']], 2)
# Assign cluster labels
comic_con['cluster_labels'], distortion_list =vq(comic_con[['x_scaled', 'y_scaled']], cluster_centers, check_finite=True)
# Plot clusters
sns.scatterplot(x='x_scaled', y='y_scaled',
hue='cluster_labels', data = comic_con)
plt.show()
#Runtime of k-means clustering
#
#Recall that it took a significantly long time to run hierarchical clustering. How long does it take to run the kmeans() function on the FIFA dataset?
#
#The data is stored in a Pandas data frame, fifa. scaled_sliding_tackle and scaled_aggression are the relevant scaled columns. timeit and kmeans have been imported.
#
#Cluster centers are defined through the kmeans() function. It has two required arguments: observations and number of clusters. You can use %timeit before a piece of code to check how long it takes to run. You can time the kmeans() function for three clusters on the fifa dataset.
%timeit kmeans(fifa[['scaled_sliding_tackle', 'scaled_aggression']], 3) | true |
5ca2cf2b0365dd45d8f5ff5dc17b8e21d6ab751f | remichartier/002_CodingPractice | /001_Python/20210829_1659_UdacityBSTPractice/BinarySearchTreePractice_v00.py | 1,210 | 4.25 | 4 | """BST Practice
Now try implementing a BST on your own. You'll use the same Node class as before:
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
This time, you'll implement search() and insert(). You should rewrite search() and not use your code from the last exercise so it takes advantage of BST properties. Feel free to make any helper functions you feel like you need, including the print_tree() function from earlier for debugging. You can assume that two nodes with the same value won't be inserted into the tree.
Beware of all the complications discussed in the videos!
Start Quiz
Provided :
"""
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
pass
def search(self, find_val):
return False
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
print tree.search(4)
# Should be False
print tree.search(6)
| true |
c7f1a592ba1dc81f24bc3097fbde5f0784eecd35 | remichartier/002_CodingPractice | /001_Python/20210818_2350_UdacityQuickSortAlgo/QuickSorAlgoPivotLast_v01.py | 1,305 | 4.1875 | 4 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
# Note : method always starting with last element as pivot
def quicksort(array):
# quick sort with pivot
# Then quick sort left_side of pivot and quick_sort right side of pivot
# Then combine left_array + Pivot + Right Array
# but reminder : it is an "in place" Algorithm
#left = 0
#right = len(array) -1
def sort(left,right):
pivot = right
#for pos in range(left,right + 1):
pos = left
while pos != pivot and pos < right :
# compare value at pos and value at pivot
# if array(pivot) < array(pos), need to move pivot...
if array[pivot] < array[pos]:
tmp = array[pos]
array[pos] = array[pivot-1]
array[pivot-1] = array[pivot]
array[pivot] = tmp
pivot -= 1
pos = left
else:
pos +=1
# end loop
# Now sort right array, since left array already sorted
if left < pivot -1:
sort(left,pivot-1)
if pivot+1 < right:
sort(pivot+1,right)
sort(0,len(array)-1)
return array
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print(quicksort(test)) | true |
d975dee37afc80c487f6ff0b1723697f340b2448 | ZeroDestru/aula-1-semestre | /aulas/oitavo3.py | 1,764 | 4.125 | 4 | import turtle
myPen = turtle.Turtle()
myPen.tracer(5)
myPen.speed(5)
myPen.color("blue")
# This function draws a box by drawing each side of the square and using the fill function
def box(intDim):
myPen.begin_fill()
# 0 deg.
myPen.forward(intDim)
myPen.left(90)
# 90 deg.
myPen.forward(intDim)
myPen.left(90)
# 180 deg.
myPen.forward(intDim)
myPen.left(90)
# 270 deg.
myPen.forward(intDim)
myPen.end_fill()
myPen.setheading(0)
boxSize = 25
#Position myPen in top left area of the screen
myPen.penup()
myPen.forward(-100)
myPen.setheading(90)
myPen.forward(100)
myPen.setheading(0)
##Here is an example of how to draw a box
#box(boxSize)
##Here are some instructions on how to move "myPen" around before drawing a box.
#myPen.setheading(0) #point to the right, 90 to go up, 180 to go to the left 270 to go down
#myPen.penup()
#myPen.forward(boxSize)
#myPen.pendown()
#Here is how your PixelArt is stored (using a "list of lists")
pixels = [[0,0,1,0,0,0,0,0,1,0,0]]
pixels.append([0,0,0,1,0,0,0,1,0,0,0])
pixels.append([0,0,1,1,1,1,1,1,1,0,0])
pixels.append([0,1,1,1,0,1,0,1,1,1,0])
pixels.append([1,1,1,1,1,1,1,1,1,1,1])
pixels.append([1,0,1,1,1,1,1,1,1,0,1])
pixels.append([1,0,1,0,0,0,0,0,1,0,1])
pixels.append([0,0,0,1,1,0,1,1,0,0,0])
for i in range (0,len(pixels)):
for j in range (0,len(pixels[i])):
if pixels[i][j]==1:
box(boxSize)
myPen.penup()
myPen.forward(boxSize)
myPen.pendown()
myPen.setheading(270)
myPen.penup()
myPen.forward(boxSize)
myPen.setheading(180)
myPen.forward(boxSize*len(pixels[i]))
myPen.setheading(0)
myPen.pendown()
myPen.getscreen().update()
| true |
92f0837d2b94b72d013e7cb41d72ef7f5c78fdf8 | HYnam/MyPyTutor | /W2_Input.py | 1,110 | 4.375 | 4 | """
Input and Output
Variables are used to store data for later use in a program. For example, the statement
word = 'cats'
assigns the string 'cats' to the variable word.
We can then use the value stored in the variable in an expression. For example,
sentence = 'I like ' + word + '!'
will assign the string 'I like cats!' to the variable sentence.
When creating a variable, we can use any name we like, but it’s better to choose a name which makes clear the meaning of the value in the variable.
The first two lines of the provided code will ask the user to input two words, and will store them in variables word1 and word2. Below that is a call to the print function which outputs the value in a variable combined. Write an assignment statement in the space between that adds the strings word1 and word2, and stores the result in the variable combined.
For example, if the words reap and pear are input, the output should be reappear.
"""
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
# Write your code in the space here:
combined = word1 + word2
print(combined) | true |
c21a9037c094373b18800d86a8a5c64ea1beb0f7 | HYnam/MyPyTutor | /W6_range.py | 711 | 4.53125 | 5 | """
Using Range
The built-in function range returns an iterable sequence of numbers.
Write a function sum_range(start, end) which uses range to return the sum of the numbers from start up to, but not including, end. (Including start but excluding end is the default behaviour of range.)
Write a function sum_evens(start, end) which does the same thing, but which only includes even numbers. You should also use range.
"""
def sum_range(start, end):
x = range(start, end)
count = 0
for n in x:
count += n
return count
def sum_evens(start, end):
count = 0
for i in range(start, end, 1):
if(i % 2 == 0):
count += i
return count | true |
0fbe09ab6841a44123707d905ee14be14e03fc53 | HYnam/MyPyTutor | /W12_recursive_base2dec.py | 354 | 4.125 | 4 | """
Recursively Converting a List of Digits to a Number
Write a recursive function base2dec(digits, base) that takes the list of digits in the given base and returns the corresponding base 10 number.
"""
def base2dec(digits, base):
if len(digits) == 1:
return digits[0]
else:
return digits[-1] + base * base2dec(digits[:-1], base) | true |
8dc081fad4227c0456266c0eab5ae3fcf5ed4d36 | HYnam/MyPyTutor | /W7_except_raise.py | 1,736 | 4.5625 | 5 | """
Raising an Exception
In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place.
One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.)
Write a function validate_input(string) which takes a command string in the format 'command arg1 arg2' and returns the pair ('command', [arg1, arg2]), where arg1 and arg2 have been converted to floats. If the command is not one of 'add', 'sub', 'mul', or 'div', it must raise InvalidCommand. If the arguments cannot be converted to floats, it must raise InvalidCommand.
"""
class InvalidCommand(Exception):
pass
def validate_input(string):
"""
If string is a valid command, return its name and arguments.
If string is not a valid command, raise InvalidCommand
Valid commands:
add x y
sub x y
mul x y
div x y
Parameters:
string(str): a valid command (see above)
Return:
tuple<str, list<float>>: the command and its corresponding arguements
Precondition:
Arguments x and y must be convertable to float.
"""
# your code here
lst = string.split(' ')
commands = ['add', 'sub', 'mul', 'div']
if lst[0] not in commands:
raise InvalidCommand()
if len(lst) != 3:
raise InvalidCommand()
try:
arg1 = float(lst[1])
arg2 = float(lst[2])
return(lst[0], [arg1, arg2])
except ValueError:
raise InvalidCommand() | true |
dc68b3a0f41f752b188744d0e1b0cdb547682b11 | HYnam/MyPyTutor | /W3_if_vowels.py | 1,070 | 4.5 | 4 | """
If Statements Using Else
In the previous question, we used an if statement to run code when a condition was True. Often, we want to do something if the condition is False as well. We can achieve this using else:
if condition:
code_if_true
[code_if_true...]
else:
code_if_false
[code_if_false...]
Here, if condition evaluates to False, then Python will run the block of code under the else statement.
For example, this code will print 'Python':
x = 0
if x > 1:
print('Monty')
else:
print('Python')
Prompt the user to enter a character, and then print either 'vowel' or 'consonant' as appropriate.
You may use the is_vowel function we’ve provided. You can call this with is_vowel(argument) e.g. vowel_or_not = is_vowel(a_variable). Alternatively you can just perform the logical test in the if condition.
"""
l = input("Enter the character: ")
if l.lower() in ('a', 'e', 'i', 'o', 'u'):
print("vowel")
elif l.upper() in ('A', 'E', 'I', 'O', 'U'):
print("vowel")
else:
print("consonant") | true |
d8bdbbf1e4426b928b14400e35938562cffaa83d | zwiktor/Checkio_zadania | /Split_list.py | 676 | 4.25 | 4 | # https://py.checkio.org/en/mission/split-list/
def split_list(items: list) -> list:
half_list = len(items)//2
if len(items) % 2 == 1:
half_list += 1
return [items[:half_list], items[half_list:]]
if __name__ == '__main__':
print("Example:")
print(split_list([1, 2, 3, 4, 5, 6]))
# These "asserts" are used for self-checking and not for an auto-testing
assert split_list([1, 2, 3, 4, 5, 6]) == [[1, 2, 3], [4, 5, 6]]
assert split_list([1, 2, 3]) == [[1, 2], [3]]
assert split_list([1, 2, 3, 4, 5]) == [[1, 2, 3], [4, 5]]
assert split_list([1]) == [[1], []]
assert split_list([]) == [[], []]
print("Coding completed") | false |
edb7cb3c4ee6562817d60924828836e66eed9011 | PraveshKunwar/python-calculator | /Volumes/rcc.py | 410 | 4.125 | 4 | import math
def rccCalc():
print("""
Please give me radius and height!
Example: 9 10
9 would be radius and 10 would be height!
""")
takeSplitInput = input().split()
if len(takeSplitInput) > 2 or len(takeSplitInput) < 2:
print("Please give me two numbers only to work with!")
value = (1/3)*(int(takeSplitInput[0]) ** 2)*(math.pi)*(int(takeSplitInput[1]))
print(value) | true |
32321cdb22a57d52a55354adc67bdf020828a8e1 | nitinaggarwal1986/learnpythonthehardway | /ex20a.py | 1,317 | 4.375 | 4 | # import the argv to call arguments at the script call from sys module.
from sys import argv
# Asking user to pass the file name as an argument.
script, input_file = argv
# To define a function to print the whole file passed into function as
# a parameter f.
def print_all(f):
print f.read()
# To define a rewind function to bring the current location on file back to
# starting position.
def rewind(f):
f.seek(0)
# To define a function that will print the line at the position given bytearray
# line_count in the file f.
def print_a_line(line_count, f):
print line_count, f.readline()
# To open the input_file in the variable name current_file.
current_file = open(input_file)
print "First let's print the whole file: \n"
# To print the whole of the file using print_all function.
print_all(current_file)
print "Now let's rewind, kind of like a tape."
# To rewind the file to the original location so that it can be read from the
# start again.
rewind(current_file)
print "Let's print three lines:"
# To print the first three lines of the file by a consecutive calls of
# print_a_line function.
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file) | true |
8872d33049899b976831cea4e01e8fc73f88ebef | bvsbrk/Learn-Python | /Basics/using_super_keyword.py | 684 | 4.46875 | 4 | class Animal:
name = "animal"
"""
Here animal class have variable name with value animal
Child class that is dog have variable name with value dog
So usually child class overrides super class so from child class
If we see the value of name is dog
To get the value of super class we use 'super' :keyword
"""
def __init__(self):
print("Super class constructor was called")
class Dog(Animal):
name = "dog"
def __init__(self):
print(self.name) # Prints dog
print(super().name) # Prints animal
super(Dog, self).__init__() # Super class constructor was called here
def main():
dog = Dog()
main()
| true |
9b9a3cc0ceb807373aa9c542ba8f3de0a28436e6 | eazapata/python | /Ejercicios python/PE5/PE5E10.py | 288 | 4.1875 | 4 | #Escribe un programa que pida la altura de un
#triángulo y lo dibuje de la siguiente
#manera:
alt=int(input("Introduce la altura del triangulo\n"))
simb=("*")
for i in range (alt):
print (" "*(alt-1)+simb)
simb=simb+"**"
alt=alt-1
| false |
7ae4858f192bbbc1540e1fb3d8a3831e6a04f6e9 | CodeItISR/Python | /Youtube/data_types.py | 979 | 4.59375 | 5 | # KEY : VALUE - to get a value need to access it like a list with the key
# key can be string or int or float, but it need to be uniqe
# Creating an dictionary
dictionary = {1: 2 ,"B": "hello" , "C" : 5.2}
# Adding a Key "D" with value awesome
dictionary["D"] = "awesome"
print(dictionary["D"])
# Print the dictionary as list of tuples
print(list(dictionary.items()))
#====================
# tuple is like a list except its static, cant change the values
# 1 item tuple need to be with comma (50, )
# Create a tuple variable
tup = (1,2,3)
# Print the second item
print(tup[1])
#====================
# multi dimensional list
# contain list that have items that can be list
# set the variable to be a list with list item
list_of_lists = [[1,2,3], ["hello", "1"], 5]
print(list_of_lists[0]) # print the first item - [1,2,3]
print(list_of_lists[1][0]) # print the first item in the second item of the all list - hello
print(list_of_lists[2]) # print the third item - 5
| true |
475fe0c425bd46ed406d2ce6492b2b0c0768d7c6 | scidam/algos | /algorithms/intervieweing.io/max_prod.py | 580 | 4.125 | 4 | # find maximum product of two integers in array
#
arr = [-1, 4, 9, -10, -8]
def max_prod(arr):
""" Find maximum product of 2 ints """
fmax = smax = fmin = smin = arr[0]
for k in range(len(arr)):
if arr[k] > fmax:
fmax = arr[k]
if arr[k] < fmin:
fmin = arr[k]
for k in range(len(arr)):
if arr[k] > smax and arr[k] != fmax:
smax = arr[k]
if arr[k] < smin and arr[k] != fmin:
smin = arr[k]
return max(fmin * smin, fmax * smax)
print("Expected value is 80: ", max_prod(arr))
| false |
4c8aaf045dae040ed39b071d4e054765b7dfd3f5 | scidam/algos | /algorithms/intervieweing.io/shuffle_fy.py | 324 | 4.21875 | 4 | # Shuffle input array using Fisher-Yates algorithm
import random
arr = list(range(10))
def shuffle(arr):
n = len(arr)
for j in range(len(arr)-1):
i = random.randint(0, j)
arr[i], arr[j] = arr[j], arr[i]
return arr
print("Before shuffling: ", arr)
print("After shuffling: ", shuffle(arr)) | false |
a1c2a407f9e3c3bac070a84390674c519ca8ed63 | scidam/algos | /algorithms/sorting/bubble.py | 1,446 | 4.21875 | 4 | __author__ = "Dmitry E. Kislov"
__created__ = "29.06.2018"
__email__ = "kislov@easydan.com"
def bubble_sort(array, order='asc'):
"""Bubble sorting algorithm.
This is a bit smart implementation of the bubble sorting algoritm.
It stops if obtained sequence is already ordered.
**Parameters**
:param array: an iterable to be sorted
:param order: a string, defines ordering, default value is `asc`
(that is ascending order)
:type array: list, tuple
:type order: string
:returns: sorted list of input values
:rtype: list
"""
from operator import lt, gt
n = len(array)
sorted_array = list(array)
comparison = lt if order == 'desc' else gt
for j in range(n):
done = True
for i in range(n - j - 1):
if comparison(sorted_array[i], sorted_array[i + 1]):
sorted_array[i + 1], sorted_array[i] = \
sorted_array[i], sorted_array[i + 1]
done = False
if done:
break
return sorted_array
if __name__ == '__main__':
array = range(10)
print("Source array: {}".format(array))
sorted_array = bubble_sort(array)
print("Sorted array: {}".format(sorted_array))
array_reversed = range(10)[::-1]
print("Reversed array: {}".format(array_reversed))
sorted_array = bubble_sort(array_reversed)
print("Sorted array: {}".format(sorted_array))
| true |
3d4f2c0e283d492aef64578a2e3fb3ebf24bf42f | SakshamMalik99/Python-Mastery | /List/List5.py | 973 | 4.15625 | 4 | print("Program :5 :")
# *number : number of time List.
list1 = [1, 3, 5]
print(list1*2)
list1 = ['Data Structure', 'C', 'C++', 'Java', 'Unix',
'DBMS', 'Python', 'SQL', 'IBM', 'Microsoft', 'Apple']
print("Orignal list is ", list1)
for data in list1:
print(data)
list1 = [1, 3, 5, 7, 17, 9, 19, 7, 113, 7, 121, 7]
print("Orignal list is ", list1)
c = list1.count(7)
print(7, " comes ", c, " times") # 4
list1 = [1, 3, 5, 7, 17, 9, 19, 7, 113, 7, 121, 7]
print("Orignal list is ", list1)
print("Number of items in list : ", len(list1)) # 12
list1.sort()
print("Orignal list is ", list1)
list1.reverse()
print("list After Reverse: ", list1)
print(list1)
list1.pop(4)
print("Orignal list is ", list1)
print("The Element is ", list1.pop(0))
pow1 = [2 ** x for x in range(10)]
print(pow1)
pow2 = []
for x in range(10):
pow2.append(2 ** x)
print(pow2)
print("List: ", end="")
for i in pow2:
print(i, end=", ")
| false |
30cf241927d7fb24f62b6ec3afd4952e05d01032 | KrisztianS/pallida-basic-exam-trial | /namefromemail/name_from_email.py | 512 | 4.40625 | 4 | # Create a function that takes email address as input in the following format:
# firstName.lastName@exam.com
# and returns a string that represents the user name in the following format:
# last_name first_name
# example: "elek.viz@exam.com" for this input the output should be: "Viz Elek"
# accents does not matter
email = input("Give me your email adress: ")
def name_from_email(email):
name = email.split("@")
split_name = name[0].split(".")
split_name.reverse()
return (' '.join(split_name))
print(name_from_email(email))
| true |
ea2638797b8f339b3a16f09b52a918690b1df4e6 | karacanil/Practice-python | /#13.py | 243 | 4.15625 | 4 | #13
inp=int(input('How many fibonnaci numbers you want me to generate:\n'))
def fibonnaci(num):
counter=0
x=1
y=0
while counter<num:
print(x)
temp=x
x+=y
y=temp
counter+=1
fibonnaci(inp)
| false |
b3561a5180fc2c219f1b7fa97a663de9ea0be793 | Whitatt/Python-Projects | /Database1.py | 1,057 | 4.25 | 4 |
import sqlite3
conn = sqlite3.connect('database1.db')
with conn:
cur = conn.cursor() #Below I have created a table of file list
cur.execute("CREATE TABLE IF NOT EXISTS tbl_filelist(ID INTEGER PRIMARY KEY AUTOINCREMENT, \
col_items TEXT)") # in the file list, i have created a column of items.
conn.commit()
conn = sqlite3.connect('database1.db')
#tuple of items
items_tuple = ('information.docx', 'Hello.txt', 'myImage.png', 'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg')
# loop through each object in the tuple to find the filelist that ends in .txt
for x in items_tuple:
if x.endswith('.txt'):
with conn:
cur = conn.cursor()
#the value for each row will be one filelist out of the tuple therefore (x,)
# will denote a one element tuple for each filelist ending with .txt
cur.execute("INSERT INTO tbl_filelist (col_items) VALUES (?)", (x,))
print(x)
conn.close()
#the output should be
#Hello.txt
#World.txt
| true |
7d32b260a8251dfe0bd111e615f8c84975d7102c | zarkle/code_challenges | /codility/interviewing_io/prechallenge2.py | 2,097 | 4.1875 | 4 | """
Mary has N candies. The i-th candy is of a type represented by an interger T[i].
Mary's parents told her to share the candies with her brother. She must give him exactly half the candies. Fortunately, the number of candies N is even.
After giving away half the candies, Mary will eat the remaining ones. She loves variety, so she wants to have candies of various types. Can you find the maximum number of different types of candy that Mary can eat?
Write a function:
[Java] class Solution { puiblic int solution(int[] T); }
[Python] def solution(T)
that, given an array T of N integers, representing all the types of candies, returns the maximum possible number of different types of candy that Mary can eat after she has given N/2 candies to her brother.
For example, given:
T = [3, 4, 7, 7, 6, 6]
the function should return 3. One optimal strategy for Mary is to give away one candy of type 4, one of type 7 and one of type 6. The remaining candies would be [3, 7, 6]: three candies of different types.
Given:
T = [80, 80, 1000000000, 80, 80, 80, 80, 80, 80, 123456789]
the function should also return 3. Here, Mary starts with ten candies. She can give away five candies of type 80 and the remaining candies would be [1000000000, 123456789, 80, 80, 80]. There are only three different types in total, i.e. 80, 1000000000 and 123456789.
Write an efficient algorithm for the following assumptions:
- N is an integer within the range [2 .. 100,000];
- N is even;
- each element of array T is an integer with the range
"""
def candy(candies):
diff = set(candies)
if len(diff) > len(candies) // 2:
return len(candies) // 2
else:
return len(diff)
def solution(T):
diff_candies = set(T)
if len(diff_candies) < len(T) // 2:
return len(diff_candies)
return len(T) // 2
print(candy([3, 4, 7, 7, 6, 6]))
# returns 3
print(candy([80, 80, 1000000000, 80, 80, 80, 80, 80, 80, 123456789]))
# returns 3
print(candy([1, 1, 7, 7, 6, 6]))
# returns 3
print(candy([1, 7, 7, 7]))
# returns 2
print(candy([7, 7, 7, 7]))
# returns 1
| true |
ba81db6eb0340d66bc8151f3616069d4d6a994a0 | zarkle/code_challenges | /dsa/recursion/homework_solution.py | 2,026 | 4.3125 | 4 | def fact(n):
"""
Returns factorial of n (n!).
Note use of recursion
"""
# BASE CASE!
if n == 0:
return 1
# Recursion!
else:
return n * fact(n-1)
def rec_sum(n):
"""
Problem 1
Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer
For example, if n=4 , return 4+3+2+1+0, which is 10.
This problem is very similar to the factorial problem presented during the introduction to recursion. Remember, always think of what the base case will look like. In this case, we have a base case of n =0 (Note, you could have also designed the cut off to be 1).
In this case, we have: n + (n-1) + (n-2) + .... + 0
"""
if n == 0:
return 0
else:
return n + rec_sum(n - 1)
# using helper function
def helper(n, sum):
if n == 0:
return sum
sum += n
return helper(n-1, sum)
return helper(n, 0)
def sum_func(n):
"""Given an integer, create a function which returns the sum of all the individual digits in that integer. For example: if n = 4321, return 4+3+2+1"""
if len(str(n)) == 1:
return n
else:
return n % 10 + sum_func(n // 10)
# using helper function
def helper(n, sum):
if len(str(n)) == 1:
sum += n
return sum
sum += n % 10
return helper(n // 10, sum)
return helper(n, 0)
def word_split(phrase,list_of_words, output = None):
"""
Note, this is a more advanced problem than the previous two! It aso has a lot of variation possibilities and we're ignoring strict requirements here.
Create a function called word_split() which takes in a string phrase and a set list_of_words. The function will then determine if it is possible to split the string in a way in which words can be made from the list of words. You can assume the phrase will only contain words found in the dictionary if it is completely splittable.
"""
pass | true |
95ceaa512a7cf774c5ca911f131109f93dc55c50 | zarkle/code_challenges | /hackerrank/25_python_if_else.py | 269 | 4.125 | 4 | # https://www.hackerrank.com/challenges/py-if-else/problem
#!/bin/python3
N = int(input())
if N % 2 == 1:
print('Weird')
if N % 2 == 0:
if 1 < N < 6:
print('Not Weird')
elif 5 < N < 21:
print('Weird')
else:
print('Not Weird') | false |
84ba5a4f2a1b9761148d8ec7c803bb7732f3e75a | zarkle/code_challenges | /fcc_pyalgo/07_minesweeper.py | 1,491 | 4.5 | 4 | """
Write a function that wil take 3 arguments:
- bombs = list of bomb locations
- rows
- columns
mine_sweeper([[0,0], [1,2]], 3, 4)
translates to:
- bomb at row index 0, column index 0
- bomb at row index 1, column index 2
- 3 rows (0, 1, 2)
- 4 columns (0, 1, 2, 3)
[2 bomb location coordinates in a 3x4 matrix]
we should return a 3 x 4 array (-1) = bomb
(ends up deleting this stuff because he changed the original bomb location from [0,1] to [1,2]) [[-1, -1, 1, 0], [2, 2, 1, 0], the 2 bombs means 2 bombs in surrounding cells [1,0] knows [0,0] and [0,1] have ...?... 0,0,0,0]]
Visualization: https://goo.gl/h4h4ax
similar: https://leetcode.com/problems/minesweeper/
"""
def minesweeper(bombs, rows, cols):
# build field using 2 for loops in one line, place 0 in each cell
field = [[0 for i in range(cols)] for j in range(rows)]
# bomb locations change from 0 to -1
for location in bombs:
(bomb_row, bomb_col) = location
field[bomb_row][bomb_col] = -1
# go through rows and columns to find bombs (check numerical value of cell); can put these directly in for loop, it's separate just for visualization
row_range = range(bomb_row - 1, bomb_row + 2)
col_range = range(bomb_col - 1, bomb_col + 2)
for i in row_range:
for j in col_range:
if 0 <= i < rows and 0 <= j < cols and field[i][j] != -1:
field[i][j] += 1
return field
print(minesweeper([[0, 0], [1, 2]], 3, 4))
| true |
c2a5429480d3c26fefd305b728e27c8fe7824ebf | zarkle/code_challenges | /hackerrank/16_tree_postorder_trav.py | 783 | 4.21875 | 4 | # https://www.hackerrank.com/challenges/tree-postorder-traversal/problem
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def postOrder(root):
#Write your code here
traverse = ''
def _walk(node=None):
nonlocal traverse
if node is None:
return
if node.left:
_walk(node.left)
if node.right:
_walk(node.right)
traverse += str(node.info) + ' '
_walk(root)
return print(traverse[:-1])
# simpler
def postOrder(root):
#Write your code here
if root:
postOrder(root.left)
postOrder(root.right)
print(root.info, end=' ') | true |
7624dfe6435e1575121da552c169df512f974c24 | rxu17/physics_simulations | /monte_carlo/toy_monte_carlo/GluonAngle.py | 1,025 | 4.1875 | 4 | # Rixing Xu
#
# This program displays the accept and reject method - generate a value x with a pdf(x) as the gaussian distribution.
# Then generate a y value where if it is greater than the pdf(x), we reject that x, otherwise we accept it
# Physically, the gluon is emitted from the quark at an angle
# Assumptions: the gluon is emitted between 0 and pi/2 radians, and its angle has a gaussian distribution
import math
import random
import matplotlib.pyplot as plt
angles = []
mean = math.pi/2 # sets the mean and std for the gaussian function
std = 2
while len(angles) != 1000:
x = random.random()*(math.pi/2.00) # our generated angle to accept or reject
y = random.random()
g = math.exp((-(x-mean)**2)/(2*std))/(2*math.sqrt(std*math.pi)) # gaussian density distribution personalized for gluon angle
if g >= y:
angles.append(x)
plt.hist(angles, bins = 20, normed = True)
plt.title("Distribution of Gluon Angle")
plt.xlabel("Angle of emitted gluon")
plt.ylabel("Density")
plt.show()
| true |
c6be4757dcfe28f09cee4360444ede6068058a8b | omarMahmood05/python_giraffe_yt | /Python Basics/13 Dictionaries.py | 786 | 4.40625 | 4 | # Dict. in python is just like dicts in real life. You give a word and then assign a meaning to it. Like key -> An instrument used to open someting speciftc.
# In python we do almost the same give a key and then a value to it. For eg Jan -> January
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sept": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}
print(monthConversions["Sept"])
print(monthConversions.get("Mar"))
#Using get is much better than using [] because you can add a default value incase the key is not found for eg ->
print(monthConversions.get("Afr", "Key Not Found")) | true |
e03f5102f11516c3c3fd7afb465799879f79c6a0 | ritomar/ifpi-386-2017-1 | /Lista03_Q04.py | 815 | 4.125 | 4 | # 4. A seqüência de Fibonacci é a seguinte:
# 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
# Sua regra de formação é simples: os dois primeiros elementos são 1;
# a partir de então, cada elemento é a soma dos dois anteriores.
# Faça um algoritmo que leia um número inteiro calcule o seu número
# de Fibonacci. F1 = 1, F2 = 1, F3 = 2, etc.
def Fibonacci(n):
t0 = 1
t1 = 1
if n == 1:
return fib = str(t0)
elif n == 2:
return fib = str(t0) + " " + str(t1)
elif n > 2:
for i in range (3, n + 1):
tn = t0 + t1
fib = fib + " " + str(tn)
t0, t1 = t1, tn
return fib
else:
return "Quantidade inválida de termos."
k = int(input("Quantidade de Termos para Fibonacci: "))
print(Fibonacci(k))
| false |
2781aceb1adfff0d5da87946d824572779f73c8e | mdeng1110/Computing_Talent_Initiative | /9_P3_Min_Stack.py | 1,041 | 4.125 | 4 | class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = 999
def push(self, x):
"""
:type x: int
:rtype: None
"""
if x <= self.min:
self.stack.append(self.min)
self.min = x
self.stack.append(x)
def pop(self):
"""
:rtype: None
"""
if self.stack:
tmp = self.stack[-1]
self.stack.pop()
if self.min == tmp:
self.min = self.top()
self.stack.pop()
def top(self):
"""
:rtype: int
"""
if self.stack:
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min
# Your MinStack object will be instantiated and called as such:
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin()) | false |
a1a726746b3b41b70fedef537c27a5da6c313d28 | mdeng1110/Computing_Talent_Initiative | /7_P3_Evaluate_Expression.py | 893 | 4.125 | 4 | def evaluate_expression(expression):
# create empty stack - > stack = []
stack = []
# loop over the expression
for element in expression:
if element.isnumeric():
stack.append(int(element))
else:
#print('STACK: ', stack)
if element == "*":
a = stack.pop()
b = stack.pop()
stack.append(b * a)
elif element == "/":
a = stack.pop()
b = stack.pop()
stack.append(b // a)
if element == "+":
a = stack.pop()
b = stack.pop()
stack.append(a + b)
elif element == "-":
a = stack.pop()
b = stack.pop()
stack.append(b - a)
return stack.pop(-1)
print(evaluate_expression(["3", "4", "+", "5", "-"]))
print(evaluate_expression(["3", "4", "/", "5", "*"]))
#print(evaluate_expression(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) | false |
2935d9e5617f497d5eb145bc473650ab021d996a | huangqiank/Algorithm | /leetcode/sorting/sort_color.py | 1,112 | 4.21875 | 4 | # Given an array with n objects colored red,
# white or blue, sort them in-place
# so that objects of the same color are adjacent,
# with the colors in the order red, white and blue.
# Here, we will use the integers
# 0, 1, and 2 to represent the color red, white, and blue respectively.
# Note: You are not suppose to use the library's sort function for this problem.
# Example:
# Input: [2,0,2,1,1,0]
# Output: [0,0,1,1,2,2]
class Solution:
def sortColors(self, nums):
if not nums:
return nums
p=0
q = len(nums)-1
self.quick_sort(nums,p,q)
def quick_sort(self,nums,p,q):
if p<q:
d = self.quick_sort_help(nums,p,q)
self.quick_sort(nums,d+1,q)
self.quick_sort(nums,p,d-1)
def quick_sort_help(self,nums,p,q):
j = p-1
for i in range(p,q):
if nums[i] < nums[q]:
j+=1
nums[i],nums[j] = nums[j],nums[i]
j+=1
nums[j],nums[q] = nums[q],nums[j]
return j
a= "abcdef"
print(a[:3])
print(a[:3] + "e" + a[3:])
print(a[6:])
print(a[0]) | true |
317f0783b9e840b41f9d422896475d5d76949889 | huangqiank/Algorithm | /leetcode/tree/binary_tree_level_order_traversal2.py | 1,205 | 4.15625 | 4 | ##Given a binary tree, return the bottom-up level order traversal of its nodes' values.
# (ie, from left to right, level by level from leaf to root).
##For example:
##Given binary tree [3,9,20,null,null,15,7],
## 3
## / \
## 9 20
## / \
## 15 7
##return its bottom-up level order traversal as:
##[
## [15,7],
## [9,20],
## [3]
##]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root):
if not root:
return
res = []
queue = [[root]]
self.levelOrderBottom_help(queue, res)
def levelOrderBottom_help(self, queue, res):
while queue:
this_Level = []
cur = queue.pop(0)
tmp =[]
for node in cur:
this_Level.append(node.val)
if node.left:
tmp.append(node.left)
if node.right:
tmp.append(node.right)
if len(tmp) > 0:
queue.append(tmp)
res.append(this_Level)
res.reverse()
return res
| true |
f07911a813545ba8213b8500356406cd1a3fb8af | Hyeongseock/EulerProject | /Problem004.py | 1,832 | 4.15625 | 4 | '''
Largest palindrome product
Problem 4
'''
'''
English version
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
#Make empty list to add number
number_list = []
#the first number is 100 because of 3-digit number
for i in range(100, 999) :
for j in range(100, 999) :
number = i * j
number = str(number) #transforming from integer to string for checking each digit number
if len(number) == 6 : #check number's lenth
if number[0]==number[5] and number[1]==number[4] and number[2]==number[3] : #check whether the number is palindrome
number_list.append(int(number))
print(max(number_list))
#time spent : 0.312 seconds
'''
Korean version
앞에서부터 읽을 때나 뒤에서부터 읽을 때나 모양이 같은 수를 대칭수(palindrome)라고 부릅니다.
두 자리 수를 곱해 만들 수 있는 대칭수 중 가장 큰 수는 9009 (= 91 × 99) 입니다.
세 자리 수를 곱해 만들 수 있는 가장 큰 대칭수는 얼마입니까?
'''
#숫자를 넣어줄 리스트를 생성
number_list = []
#세 자리 수 두개를 곱해야 하므로 최초의 값은 100
for i in range(100, 999) :
for j in range(100, 999) :
number = i * j
number = str(number) #각각의 자리수에 어떤 숫자가 있는지 체크하기 위해 integer에서 string으로 타입 변환
if len(number) == 6 : #6자리인지 체크
if number[0]==number[5] and number[1]==number[4] and number[2]==number[3] : #대칭수인지 체크
number_list.append(int(number))
print(max(number_list))
#걸린 시간 : 0.312 seconds
| true |
88021e789e0602fff3527af5edd82e2db4e5376c | omolea/BYUI_CS101 | /week_02/team_activity.py | 2,155 | 4.15625 | 4 | """
Jacob Padgett
W02 Team Activity:
Bro Brian Wilson
"""
First_name = input("What is you first name: ")
Last_name = input("What is you last name: ")
Email_Address = input("What is you email: ")
Phone_Number = input("What is you number: ")
Job_Title = input("What is you job: ")
ID_Number = input("What is you id: ")
Hair_Color = input("What is your hair color: ")
Eye_Color = input("What is your eye color: ")
Month_Started = input("What is the month you started: ")
In_Training = input("Are you in training (Yes/No): ")
d = "----------------------------------------"
print("The ID Card is:")
print(d)
print(f"{Last_name.upper()}, {First_name.capitalize()}")
print(Job_Title.title())
print(ID_Number, "\n")
print(Email_Address.lower())
print(Phone_Number, "\n")
print(f"Hair: {Hair_Color.capitalize()}\t\tEyes: {Eye_Color.capitalize()}")
print(
f"Month Started: {Month_Started.capitalize()}\tTraining: {In_Training.capitalize()}"
)
print(d)
""" Below is my personal code for the assignment """
# d = "----------------------------------------"
# First_Name = input("What is your first name: ")
# Last_Name = input("What is your last name: ")
# Email_Address = input("What is your email address: ")
# Phone_Number = input("What is your phone number: ")
# Job_Title = input("What is your job title: ")
# ID_Number = input("What is your ID number: ")
# Hair_Color = input("What is your hair color: ")
# Eye_Color = input("What is your eye color: ")
# Month_Started = input("What is the month you started: ")
# In_Training = input("Are you in training (Yes/No): ")
# lst = [
# First_Name, # index 0
# Last_Name, # index 1
# Email_Address, # index 2
# Phone_Number, # index 3
# Job_Title, # index 4
# ID_Number, # index 5
# Hair_Color, # index 6
# Eye_Color, # index 7
# Month_Started, # index 8
# In_Training, # index 9
# ]
# badge = f"""
# {d}
# {lst[1].upper()}, {lst[0].capitalize()}
# {lst[4].title()}
# ID: {lst[5]}
# {lst[2].lower()}
# {lst[3]}
# Hair: {lst[6].capitalize()}\tEyes: {lst[7].capitalize()}
# Month: {lst[8].capitalize()}\tTraining: {lst[9].capitalize()}
# {d}
# """
# print(badge)
| true |
029fb3d02ca753d046ce00a6156f7ff75e8c0210 | alexisalt/curso_pensamiento_computacional | /listas.py | 1,503 | 4.4375 | 4 | my_list = [1, 2, 3]
print(my_list[0])
print(my_list[1:])
#Veremos ahora los metodos de las listas y sus side-effects
my_list.append(4)
print(my_list)
#NO EXISTIO una reasignacion, simplemente la modificamos a la lista
#agreganndole el numero 4 al final.
#modificar ahora una de las posiciones
my_list[0] = 'a' #A diferencia de otros lenguajes Python permite mezclar tipo de datos
print(my_list)
my_list.pop()
print(my_list)
#El metodo pop elimina el ultimo objeto de la lista.
print('Tambien se puede iterar con las listas')
for element in my_list:
print(element)
print('Efectos secundarios')
a = [1, 2, 3]
b = a
#Lo que estamos haciendo aqui es asignar a 'b' la lista de 'a'
#quiere decir que estamos apuntando las dos variables al mismo lugar en memoria.
print(id(a))
print(id(b))
#Por ejemplo si queremos generar una lista de listas:
c = [a, b]
print(c)
# Si al avanzar por el programa olvidamos que generamos un alias (b) y empleamos el metodo append:
a.append(5)
print(a)
#Verifiquemos:
print(c)
#Como vemos se modificaron ambas listas, porque se modifico el mismo espacio de memoria
#y dado que b apunta al mismo lugar que a, el cambio tambien se produjo sobre b.
#Para que esto no ocurra es mejor generar a 'b' como una lista independiente con su propio espacio de memoria.
b = [1, 2, 3]
print(b)
#Por esta razon usualmene se prohiben utilizar tipo de datos mutables y en cambio se utiliza
#el metodo de clonacion para generar una copia. Se vera en un archivo diferente | false |
c3f197930c850ca43bc7c7339d1ab7482ea218bc | shoel-uddin/Digital-Crafts-Classes | /programming102/exercises/list_exercises.py | 1,555 | 4.375 | 4 | #Exercise 1
# Create a program that has a list of at least 3 of your favorite
# foods in order and assign that list to a variable named "favorite_foods".
# print out the value of your favorite food by accessing by it's index.
# print out the last item on the list as well.
favorite_foods = ["Pizza", "Pasta", "Byriani"]
print (favorite_foods[2])
print (favorite_foods[-1])
# #Exercise 2
# #Create a program that contains a list of 4 different "things" around you.
# # Print out the each item on a new line with the number of it's
# # index in front of the item.
# # 0. Coffee Cup
# # 1. Speaker
# # 2. Monitor
# # 3. Keyboard
random_things = ["Mug", "Lamp", "Fan", "Boxes"]
index = 0
while index < len(random_things):
things = random_things[index]
print("%d: %s" % (index + 1, things)) #things [index]
index += 1
# #Using the code from exercise 2, prompt the user for
# # which item the user thinks is the most interesting.
# # Tell the user to use numbers to pick. (IE 0-3).
# # When the user has entered the value print out the
# # selection that the user chose with some sort of pithy message
# # associated with the choice.
# # "You chose Coffee Cup, You must like coffee!"
interests = int(input("Which do you thing is most interresting? (Pick 1-4)\n"))
if interests == 0:
print (f"You chose {random_things[0]}. You must be thursty")
elif interests == 1:
print ("You must need some light")
elif interests == 2:
print ("It must be hot lets get some air flowing")
else:
print ("would you like some to use") | true |
d652382b0e657735b15fc377cf8c087d32759c6a | shoel-uddin/Digital-Crafts-Classes | /programming102/exercises/key-value-pairs_exercise.py | 718 | 4.3125 | 4 | #1
movie = {
"name":"Star Wars",
"episode":4,
"year":"1977"
}
print (movie)
#2
person = {
"first_name": "Sho",
"last_name": "Uddin",
"age": 30,
"hair_color": "Black"
}
for key in person:
print (person[key])
print (f"Hello {person['first_name']} {person['last_name']}. Since you are {person['age']} years old you are too old to ride this ride, but you do have nice {person['hair_color']} hair.")
person1= {
"name": "sho",
"phone": 404,
"email": "sho@email.com"
}
person2= {
"name": "Lia",
"phone": 678,
"email": "lia@email.com"
}
people = [person1,person2]
for key in person1:
print(key, person1[key])
for key in person2:
print(key, person2[key]) | false |
28c51e037e37d5567b59afb6abb3cbdf40f9e64b | Eccie-K/pycharm-projects | /looping.py | 445 | 4.28125 | 4 | #looping - repeating a task a number of times
# types of loops: For loop and while loop
# modcom.co.ke/datascience
counter = 1 # beginning of the loop
while counter <= 10: # you can count from any value
print("hello", counter)
counter = counter +1 # incrementing
z = 9
while z >= -9:
print("you", z)
z = z-3
y = 1960
while y<=2060:
print("hey", y)
y = y +1
for q in range(2020, 1961, -1):
print("see", q)
| true |
deb60878e985ea2f31f2c57fd7f035db19cfbd5f | Eccie-K/pycharm-projects | /leap year.py | 330 | 4.25 | 4 | # checking whether a year is leap or not
year = int(input("enter the year in numbers:"))
if year % 4 != 0:
print("this is not a leap year")
elif year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
print("it is a leap year")
elif year % 4 == 0 and year % 100 != 0:
print("leap year")
else:
print("leap year") | false |
d1bbfae6e3467c8557852939faf5cdd1daa1f2ca | Robock/problem_solving | /interview_code_14.py | 1,127 | 4.125 | 4 | #Given a non-finite stream of characters, output an "A" if the characters "xxx" are found in exactly that sequence.
#If the characters "xyx" are found instead, output a "B".
#Do not re-process characters so as to output both an “A” and a “B” when processing the same input. For example:
#1. The following input xxyxyxxxyxxx would produce the following output: BAA
#2. The following input xxxyxyxxxxyyxyxyx would produce the following output: ABAB
def abba(sample_string):
three = ''
new_string = ''
for ch in sample_string:
if len(three) == 0:
if ch == 'x':
three += ch
else:
three = ''
elif len(three) == 1:
if ch == 'x' or ch == 'y':
three += ch
else:
three = ''
elif len(three) == 2:
if three == 'xx':
if ch == 'x':
new_string += 'A'
three = ''
elif ch == 'y':
three = 'xy'
else:
three = ''
elif three == 'xy':
if ch == 'x':
new_string += 'B'
three = ''
else:
three = ''
return new_string
print(abba('xxyxyxxxyxxx'))
print(abba('xxxyxyxxxxyyxyxyx'))
| true |
ef02434465a6d6da8ebcec85cbc10711f6660760 | wyxvincent/turtle_lesson | /poligon.py | 413 | 4.1875 | 4 | import turtle
t = turtle.Pen()
def polygon(side, length):
if side < 2:
print("2条边不足以构成多边形")
else:
angle = 180 - (side - 2) * 180 / side
for i in range(side):
t.forward(length)
t.left(angle)
turtle.done()
side = int(input("请输入多边形的边数:"))
length = int(input("请输入多边形的边长:"))
polygon(side, length) | false |
5c69c5fbd745c124255cae5cf5856026b0b6e989 | ashwin-pajankar/Python-Bootcamp | /Section15/04Dict.py | 612 | 4.15625 | 4 | dict1 = {"brand": "Intel",
"model": "8008",
"year": 1972}
print(dict1)
print(dict1["brand"])
print(dict1.get("model"))
dict1["brand"] = "AMD"
dict1["model"] = "Ryzen"
dict1["year"] = 2017
print(dict1)
for x in dict1:
print(x)
for x in dict1:
print(dict1[x])
for x in dict1.values():
print(x)
for x, y in dict1.items():
print(x, y)
print(len(dict1))
dict1["color"] = "Red"
for x, y in dict1.items():
print(x, y)
del dict1["model"]
for x, y in dict1.items():
print(x, y)
dict1.clear()
print('------')
for x, y in dict1.items():
print(x, y)
del dict1
| false |
c7b7a3f789e1481bdd819b815820bebefddb6582 | ashwin-pajankar/Python-Bootcamp | /Section09/08fact.py | 225 | 4.3125 | 4 | num = int(input("Please enter an integer: "))
fact = 1
if num == 0:
print("Factorial of 0 is 1.")
else:
for i in range (1, num+1):
fact = fact * i
print("The factorial of {0} is {1}.".format(num, fact))
| true |
787dc5e851fba1bf8819f643da671ec4b0b06462 | rubramriv73/daw1.2 | /prog/python/tareas/ejerciciosSecuenciales/ej16_coches.py | 1,518 | 4.25 | 4 | '''
@author: Rubén Ramírez Rivera
16. Dos vehículos viajan a diferentes velocidades (v1 y v2)
y están distanciados por una distancia d. El que está detrás
viaja a una velocidad mayor. Se pide hacer un algoritmo para
ingresar la distancia entre los dos vehículos (km) y sus
respectivas velocidades (km/h) y con esto determinar y mostrar
en que tiempo (minutos) alcanzará el vehículo más rápido al otro.
'''
print('\n *** PROGRAMA QUE MUESTRA EN CUANTO TIEMPO SE ENCONTRARAN 2 COCHES *** \n')
#Pedimos al usuario la distancia entre los vehiculos, la velocidad del primero
#y la velocidad del segundo
'''
Hay que tener cuenta que v2 tiene que ser mayor
que v1 ya que el segundo coche va a mayor velocidad
'''
distance = int(input('Introduce la distancia entre los vehiculos (km): '))
v1 = int(input('Introduce la velocidad del primer vehiculo (km/h): '))
v2 = int(input('Introduce la velocidad del primer vehiculo (km/h): '))
#Calculamos el tiempo que tardan en encontrarse
'''
Para calcular el tiempo que tardan en encontrarse necesitamos dividir
la distancia a la que se encuentran entre la diferencia de las
velocidades de los 2 vehiculos
time = distance / (v2 - v1)
'''
time = distance / (v2 - v1)
#Mostramos el resultado al usuario
print('\nDATOS:')
print('\nDistancia entre vehiculos = ', distance, 'km')
print('Velocidad del primer vehiculo = ', v1, 'km/h')
print('Velocidad del segundo vehiculo = ', v2, 'km/h')
print('\n\nRESULTADO:')
print('\nTiempo en encontrarse = ', (time * 60), 'min \n') | false |
71aaf25131020ba822111659bb2594904b4f8e63 | rubramriv73/daw1.2 | /prog/python/tareas/ejerciciosSecuenciales/ej15_intercambio.py | 888 | 4.28125 | 4 | '''
@author: Rubén Ramírez Rivera
15. Dadas dos variables numéricas A y B, que el usuario
debe teclear, se pide realizar un algoritmo que intercambie
los valores de ambas variables y muestre cuanto valen al
final las dos variables.
'''
print('\n *** PROGRAMA QUE INTERCAMBIA EL VALOR DE 2 VARIABLES *** \n')
#Pedimos al usuario 2 numeros
numA = int(input('Introduce un numero: '))
numB = int(input('Introduce otro numero: '))
print('\nINICIO')
print('\nPrimer numero = ' , numA)
print('Segundo numero = ' , numB, '\n')
#Intercambiamos los valores de los numeros
'''
Guardamos el primer numero en una variable auxiliar
aux = numA
Intercambiamos los valores uso de la variable auxiliar
numA = numB
numB = aux
'''
aux= numA
numA = numB
numB = aux
#Mostramos el resultado del intercambio
print('\nINTERCAMBIO')
print('\nPrimer numero = ' , numA)
print('Segundo numero = ' , numB, '\n')
| false |
718ebb2daf0753bcaeeef1bfc6c226f320000859 | zenvin/ImpraticalPythonProjects | /chapter_1/pig_latin_ch1.py | 926 | 4.125 | 4 | ## This program will take a word and turn it into pig latin.
import sys
import random
##get input
VOWELS = 'aeiouy'
while True:
word = input("Type a word and get its pig Latin translation: ")
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
print()
print("{}".format(pig_Latin), file=sys.stderr)
try_again = input("\n\nTry again? (Press Enter else n to stop)\n ")
if try_again.lower() == "n":
sys.exit()
## if input start with a vowel do the following:
## add "way" to the end of the word
## else (input starts with a consonant) do the following:
## remove the constant (cut?)
## add it to the end of the input (append?)
## add "ay" after the constant
## perhaps we can add consonant and "ay" in one line
## elseif (if the input is a number or begins with a symbol)
## print("We need a leter")
| true |
d436073bd316bd56c8c9958785e0bb18476944a7 | Soundaryachinnu/python_script | /classobj.py | 1,360 | 4.125 | 4 | #!/usr/bin/python
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
# c = Child() # instance of child
# c.childMethod() # child calls its method
# c.parentMethod() # calls parent's method
# c.setAttr(130) # again call parent's method
# c.getAttr() # again call parent's method
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vecdddtor (%d, %d)' % (self.a, self.b)
def __sub__(self,other):
return Vector(self.a - other.a, self.b - other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 - v2
class chkgreater:
def __init__(self,a,b):
self.a = a;
self.b = b;
def __str__(self):
return 'greater (%d)' % (self)
def _gt__(self,a,b):
if(self.a > self.b):
return chkgreater(self.a);
else:
return chkgreater(self.b);
print chkgreater(10,4);
| true |
f60b812a06af2b1a20d6f8c609c5c06492fe3f8c | Arsal-Sheikh/Dungeon-Escape---CS-30-Final | /gamemap.py | 2,604 | 4.25 | 4 | class Dungeon:
def __init__(self, name, riddle, answer):
"""Creates a dungeon
Args:
name (string): The name of the dungeon
riddle (string): The riddle to solve the dungeon
answer (string): The answer to the riddle
"""
self.name = name
self.riddle = riddle
self.answer = answer
def __str__(self):
"""Returns the name of the dungeon
Returns:
string: The name of the dungeon
"""
return self.name
def __len__(self):
"""Returns the length of the name of the dungeon
Returns:
int: Length of the dungeon name
"""
return len(self.name)
class GameMap:
def __init__(self, gamemap):
"""Creates a gamemap
Args:
gamemap (list[Dungeon]): A list of the dungeons in order
"""
self.gamemap = gamemap
def display(self, position):
"""Prints the dungeons out
Args:
position (int): The dungeon the player is in
"""
size = max(map(len, self.gamemap))
print(f"|{'-'*(size+2)}|")
print(f"| {'Start'.ljust(size)} |")
for i, line in enumerate(self.gamemap):
if i == position:
print(f"|{'='*(size+2)}|")
print(f"| {str(line).ljust(size)} |")
print(f"|{'='*(size+2)}|")
else:
print(f"| {str(line).ljust(size)} |")
print(f"| {'Finish'.ljust(size)} |")
print(f"|{'-'*(size+2)}|")
gamemap = GameMap(
[
Dungeon(
"Dungeon 1",
"What has to be broken before you can use it? (Hint: It's food)",
"egg",
),
Dungeon(
"Dungeon 2",
"I’m tall when I’m young, and I’m short when I’m old. What am I?",
"candle",
),
Dungeon(
"Dungeon 3",
"What month of the year has 28 days?",
"all",
),
Dungeon(
"Dungeon 4",
"What is full of holes but still holds water?",
"sponge",
),
Dungeon(
"Dungeon 5",
"What question can you never answer yes to?",
"asleep",
),
Dungeon(
"Dungeon 6",
"What is always in front of you but can’t be seen?",
"future",
),
Dungeon(
"Dungeon 7",
"What can you break, even if you never pick it up or touch it?",
"promise",
),
]
)
| true |
6030e8ed6694c33baf1b4a8851323c5adcfa9c79 | ju9501/iot-kite | /Python/func_2.py | 381 | 4.5 | 4 | # list 선언
list_a = [1, 2, 3, 4, 5]
list_b = list(range(1,6))
print(list_a)
print(list_b)
# 리스트 역순으로 뒤집는다.
list_reversed = reversed(list_a)
list_reversed = list(list_reversed)
# list 출력
print('list_a :',list_a)
print('list(list_reversed) :',list_reversed)
# for 문장을 이용해서 역순 참조
for i in reversed(list_a):
print(i)
| false |
d9736075107c9ca1f288291a0109789e658d00c1 | 1ekrem/python | /CrashCourse/chapter10/tiy103.py | 1,962 | 4.375 | 4 | '''
10-3. Guest: Write a program that prompts the user for their name. When they
respond, write their name to a file called guest.txt.
10-4. Guest Book: Write a while loop that prompts users for their name. When
they enter their name, print a greeting to the screen and add a line recording
their visit in a file called guest_book.txt. Make sure each entry appears on a
new line in the file.
10-5. Programming Poll: Write a while loop that asks people why they like
programming. Each time someone enters a reason, add their reason to a file
that stores all the responses.
'''
filename = "C://PythonClass//CrashCourse//chapter10//sampleFiles//guests.txt"
name = str(input("Can you please enter your name?: \n"))
name2 = ('{}\n').format(name)
try:
with open(filename) as read_object:
cont = read_object.readlines()
cont2 = []
for i in cont:
cont2.append(i.rstrip())
if name not in cont2:
with open(filename, 'a') as file_object:
file_object.write(name2)
print(name + " is added to the guests list. Thank you!")
else:
print(name + " is in the guest list")
print("Current Names in the file: ", cont2)
except FileNotFoundError:
print("File not found.")
print("--- NEW LINE ---")
"""
10-5. Programming Poll: Write a while loop that asks people why they like
programming. Each time someone enters a reason, add their reason to a file
that stores all the responses.
"""
filename105 = 'C://PythonClass//CrashCourse//chapter10//sampleFiles//filename105.txt'
responses = []
while True:
response = input("Why do you like programming?:\n")
responses.append(response)
continue_poll = input("Would you like to let someone else respond? (y/n) ")
if continue_poll != 'y':
break
with open(filename105, 'w') as f:
for i in responses:
f.write(i + "\n") | true |
9a6a512989a683662cb0947cc5b7ad2d3ba903e7 | 1ekrem/python | /CrashCourse/chapter8/tiy86.py | 2,533 | 4.75 | 5 | """
8-6. City Names: Write a function called city_country() that takes in the name
of a city and its country. The function should return a string formatted like this:
"Santiago, Chile"
Call your function with at least three city-country pairs, and print the value
that’s returned.
"""
def city_country(cityName, countryName):
return (cityName + ", "+ countryName)
city_1 = city_country("Santiago", "Chile")
print(city_1)
city_2 = city_country("New York City", "NY")
print(city_2)
city_3 = city_country("Barcelona", "Spain")
print(city_3)
print("------- NEW LINE --------")
"""8-7. Album: Write a function called make_album() that builds a dictionary
describing a music album. The function should take in an artist name and an
album title, and it should return a dictionary containing these two pieces of
information. Use the function to make three dictionaries representing different
albums. Print each return value to show that the dictionaries are storing the
album information correctly.
Add an optional parameter to make_album() that allows you to store the
number of tracks on an album. If the calling line includes a value for the number
of tracks, add that value to the album’s dictionary. Make at least one new
function call that includes the number of tracks on an album."""
def make_album(artistName, albumTitle, numberofTracks=''):
album = {
'Artist Name': artistName,
'Album Title': albumTitle
}
if numberofTracks:
album['Number of Tracks'] = numberofTracks
return album
artist1 = make_album("Ekrem", "Hello1")
artist2 = make_album("Daria", "Sensitive2")
artist3 = make_album("Pupsik", "Always Hungry", 3)
print(artist1)
print(artist2)
print(artist3)
"""8-8. User Albums: Start with your program from Exercise 8-7. Write a while
loop that allows users to enter an album’s artist and title. Once you have that
information, call make_album() with the user’s input and print the dictionary
that’s created. Be sure to include a quit value in the while loop."""
user_question = input("\nWould you like me to ask you some questions?: ")
if user_question.title() == 'Yes':
while True:
print("If you would like me to stop, please type 'stop' below")
artist_name = input("Enter Artist's name: ")
if artist_name == 'stop':
break
album_title = input("Enter Artist's album title: ")
artist_generation = make_album(artist_name,album_title)
print(artist_generation)
| true |
38f7a26fd5f45b93c1d1ed6669bd362a55e2f641 | 1ekrem/python | /CrashCourse/chapter8/tiy89.py | 1,670 | 4.46875 | 4 | """8-9. Magicians: Make a list of magician’s names. Pass the list to a function
called show_magicians(), which prints the name of each magician in the list."""
def show_magicians(magicians):
for name in magicians:
print(name)
names = ['Ekrem', 'Daria', 'Pupsik']
show_magicians(names)
"""8-10. Great Magicians: Start with a copy of your program from Exercise 8-9.
Write a function called make_great() that modifies the list of magicians by adding
the phrase the Great to each magician’s name. Call show_magicians() to
see that the list has actually been modified."""
print("--- New line ---")
def show_magicians2(magicians):
for magician in magicians:
print(magician)
def make_great(magicians):
#Building a new list to hold great magicians
great_magicians = []
#Make each magician great, and add it to great_magician
while magicians:
magician = magicians.pop()
great_magician = magician + " the Great"
great_magicians.append (great_magician)
for great_magician in great_magicians:
magicians.append(great_magician)
m_names = ['Tapar', 'Sencer', 'Hasan Sabbah']
show_magicians2(m_names)
print("--- New line ---")
make_great(m_names)
"""8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the
function make_great() with a copy of the list of magicians’ names. Because the
original list will be unchanged, return the new list and store it in a separate list.
Call show_magicians() with each list to show that you have one list of the original
names and one list with the Great added to each magician’s name. """
print("8-11")
| true |
8b816e4924d13dad093ea03f4967cae78eb494d5 | Lyonidas/python_practice | /Challenge-4.py | 1,759 | 4.1875 | 4 | # Preston Hudson 11/21/19 Challenge 4 Written in Python
#1. Write a function that takes a number as input and returns that number squared.
def f(x):
"""
returns x squared
:param x: int.
:return: int sum of x squared
"""
return x ** 2
z = f(4)
print(z)
#2. Create a function that accepts a string as a parameter and prints it.
def string(x):
"""
prints string
:param x: string.
:return: None
"""
print(x)
string("Hello.")
#3. Write a function that takes three required parameters and two optional parameters.
def five_letters(a, b, c, d = 4, e = 5):
"""
return the addition of a, b, c, d, and e.
:param a: int.
:param b: int.
:param c: int.
:optparam d: int.
:optparam e: int.
:return: sum of params
"""
print(a + b + c + d + e)
return a + b + c + d + e
five_letters(1, 2, 3)
#4. Write a program with 2 functions. The first function takes a integer then divides it by two. The second function takes the first functions output then multiplies it by 4.
def divided_by_two(x):
"""
returns x divided by two
:param x: int.
:return: x / 2
"""
return x / 2
def multiply_by_four(y):
"""
returns y times 4
:param y: int.
:return: y * 4
"""
return y * 4
y = divided_by_two(10)
result = multiply_by_four(y)
print(result)
#5. Write a function that converts a string into a float
def string_float(string):
"""
returns a float converted from a string
:param string: string.
:returns number:
"""
try:
number = float(string)
print(number)
return number
except ValueError:
print("Input has to me string number.")
string_float("21")
string_float("Hundo.")
#Complete
| true |
ceb3a00d884b1ee19687364f03d1755e7932c43d | Lyonidas/python_practice | /Challenge-6.py | 1,652 | 4.1875 | 4 | # Preston Hudson 11/25/19 Challenge 6 Written in Python
#1. Print every character in the string "Camus".
author = "Camus"
print(author[0])
print(author[1])
print(author[2])
print(author[3])
print(author[4])
#2. Write a program that collects two strings from the user, inserts them into a string and prints a new string.
response_one = input("Enter a noun: ")
response_two = input("Enter a place: ")
print("Yesterday I wrote a "+response_one+". I sent it to "+response_two+"!")
#3. Use a method to capitalize a string.
capital_string = "aldous Huxley was born in 1894.".capitalize()
print(capital_string)
#4. Call a method on a string that splits it into a list.
"Where now?. Who now?. When now?.".split(".")
#5. Take the list ... and turn it into a grammer correct string.
words = ["The",
"Fox",
"jumped",
"over",
"the",
"fence",
"."]
sentence = " ".join(words)
print(sentence)
#6. Replace all s's in a sentence with a $
sky = "A screaming comes across the sky."
sky = sky.replace("s", "$")
print(sky)
#7. Use a method to find the first index of the character "m" in the string "Hemingway".
print("Hemingway".index("m"))
#8. Find dialogue from your favorite book and turn it into a string.
socrates = """True knowledge, is the wisdom to admit that you know nothing."""
print(socrates[:])
#9. Create a string ... using concatination then multiplication.
print("Three "+"Three "+"Three")
print("Three " * 3)
#10. Slice the string ... to only include characters before the comma.
slice = """It was a bright cold day in April, and the clocks were striking thirteen."""
print(slice[0:34])
#Complete
| true |
9cd05b9e27b20535a31ceca3db2987fd97a85ae0 | Blasco-android/Curso-Python | /desafio60.py | 562 | 4.125 | 4 | # Calcular o Fatorial
'''
#Utilizando modulo
from math import factorial
print('''
#[ 1 ] Calcular Fatorial
#[ 0 ] Fechar Programa
''')
abrir = int(input('Escolha uma Opcão: '))
while abrir != 0:
num = int(input('Digite um valor: '))
print('O fatorial de {} é {}.'.format(factorial(num)))
'''
num = int(input('Digite um numero para calcular seu fatorial: '))
c = num
f = 1
print('Calculando {}! = '.format(num))
while c > 0:
print('{}'.format(c), end='')
print(' x ' if c > 1 else ' = ', end='')
f *= c
c -= 1
print('{}'.format(f))
| false |
76178534554fa030e42e9f7a2d23db151b282b09 | jcalahan/ilikepy | /004-functions.py | 311 | 4.15625 | 4 | # This module explores the definition and invocation of a Python function.
PI = 3.1459
def volume(h, r):
value = PI * h * (r * r)
return value
height = 42
radius = 2.0
vol = volume(height, radius)
print "Volume of a cylinder with height of %s and radius of %s is %s" \
% (height, radius, vol)
| true |
2b409cfeb923e07db625a46cf4a357cc627d5a20 | niranjan2822/Interview1 | /count Even and Odd numbers in a List.py | 1,827 | 4.53125 | 5 | # count Even and Odd numbers in a List
'''
Given a list of numbers, write a Python program to count Even and Odd numbers in a List.
Example:
Input: list1 = [2, 7, 5, 64, 14]
Output: Even = 3, odd = 2
Input: list2 = [12, 14, 95, 3]
Output: Even = 2, odd = 2
'''
# Example 1: count Even and Odd numbers from given list using for loop
#
# Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers.
# If the condition satisfies, then increase even count else increase odd count.
# Python program to count Even
# and Odd numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 1]
even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
print("Even numbers in the list: ", even_count)
print("Odd numbers in the list: ", odd_count)
# output : Even numbers in the list: 3
# Odd numbers in the list: 4
# Example 2: Using while loop
# Python program to count Even and Odd numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 11]
even_count, odd_count = 0, 0
num = 0
# using while loop
while (num < len(list1)):
# checking condition
if list1[num] % 2 == 0:
even_count += 1
else:
odd_count += 1
# increment num
num += 1
print("Even numbers in the list: ", even_count)
print("Odd numbers in the list: ", odd_count)
# Example 3 : Using Python Lambda Expressions
# list of numbers
list1 = [10, 21, 4, 45, 66, 93, 11]
odd_count = len(list(filter(lambda x: (x%2 != 0) , list1)))
# we can also do len(list1) - odd_count
even_count = len(list(filter(lambda x: (x%2 == 0) , list1)))
print("Even numbers in the list: ", even_count)
print("Odd numbers in the list: ", odd_count)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.