blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
af103d58cbf6743160c45164920ce36ad68146c2 | felipeonf/Exercises_Python | /exercícios_fixação/062.py | 911 | 4.125 | 4 | ''' Faça um programa usando a estrutura “faça enquanto” que leia a idade de
várias pessoas. A cada laço, você deverá perguntar para o usuário se ele quer ou
não continuar a digitar dados. No final, quando o usuário decidir parar, mostre
na tela:
a) Quantas idades foram digitadas
b) Qual é a média entre as idades digitadas
c) Quantas pessoas tem 21 anos ou mais.'''
print('>>>>>>>>>> Leitura de dados >>>>>>>>>>')
idades = 0
n_idades = 0
pessoas_21mais = 0
while True:
idade = int(input('Digite a sua idade: '))
n_idades += 1
idades += idade
if idade >= 21:
pessoas_21mais += 1
opcao = input('Deseja continuar?(s/n) ').strip().lower()[0]
if opcao == 'n':
break
print(f'Foram digitadas {n_idades} idades')
print('A média entre as idades é {:.2f}'.format(idades/n_idades))
print(f'{pessoas_21mais} pessoas possuem 21 ou mais anos')
| false |
7bc09ed3640e3f0e32e2ea12725a65cb87d6d39f | SavinaRoja/challenges | /Rosalind/String_Algorithms/RNA.py | 2,275 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Transcribing DNA into RNA
Usage:
RNA.py <input> [--compare]
RNA.py (--help | --version)
Options:
--compare run a speed comparison of various methods
-h --help show this help message and exit
-v --version show version and exit
"""
problem_description = """Transcribing DNA into RNA
Problem
An RNA string is a string formed from the alphabet containing 'A', 'C', 'G',
and 'U'.
Given a DNA string, t, corresponding to a coding strand, its transcribed RNA
string, u, is formed by replacing all occurrences of 'T' in t with 'U' in u.
Given: A DNA string t having length at most 1000 nt.
Return: The transcribed RNA string of t.
Sample Dataset
GATGGAACTTGACTACGTAAATT
Sample Output
GAUGGAACUUGACUACGUAAAUU
"""
from docopt import docopt
from time import time
def get_string_from_dataset(inp_file):
#The dataset should be a file with a single line, containing no more than
#1000 characters of the ACGT alphabet
with open(inp_file, 'r') as inp:
data_string = inp.readline()
return data_string.strip()
def string_replace_method(data):
return data.replace('T', 'U')
def iterative_transcribe_method(data):
rna = ''
for char in data:
if char == 'T':
rna += 'U'
else:
rna += char
return rna
def main():
"""This will solve the problem, simply uses the string_replace_method"""
data_string = get_string_from_dataset(arguments['<input>'])
print(string_replace_method(data_string))
def compare():
"""
This will seek to compare the various solutions
"""
data_string = get_string_from_dataset(arguments['<input>'])
start = time()
for i in range(1000):
string_replace_method(data_string)
print('''It took the string_replace method {0} seconds to complete 1000 \
repetitions\n'''.format(time() - start))
start = time()
for i in range(1000):
iterative_transcribe_method(data_string)
print('''It took the string_replace method {0} seconds to complete 1000 \
repetitions\n'''.format(time() - start))
if __name__ == '__main__':
arguments = docopt(__doc__, version='0.0.1')
if arguments['--compare']:
compare()
else:
main()
| true |
d122d93baa813af861b12346e82003bdc91e7d47 | Jessica-Luis001/shapes.py | /shapes.py | 1,042 | 4.46875 | 4 | from turtle import *
import math
# Name your Turtle.
marie = Turtle()
color = input("What color would you like?")
sides = input("How many sides would you like?")
steps = input("How many steps would you like?")
# Set Up your screen and starting position.
marie.penup()
setup(500,300)
x_pos = -250
y_pos = -150
marie.setposition(x_pos, y_pos)
### Write your code below:
answer = input("What color would you like?")
intanswer = int(answer)
answer = input("How many sides would you like?")
intanswer = int(answer)
marie.pendown()
marie.speed(10)
marie.pencolor(color)
def square():
marie.begin_fill()
marie.fillcolor(color)
for square in range(4):
marie.forward(50)
marie.right(90)
marie.end_fill()
print("This is a square.")
marie.penup()
square()
marie.pendown()
def large_square():
for large_square in range (4):
marie.forward(50)
marie.left(90)
marie.forward(50)
print("This is a large_square")
marie.penup()
large_square()
# Close window on click.
exitonclick()
| true |
14f15835a90bc85b84528f40622ee216d4bfd2a4 | GaloisGroupie/Nifty-Things | /custom_sort.py | 1,247 | 4.28125 | 4 | def merge_sort(inputList):
"""If the input list is length 1 or 0, just return
the list because it is already sorted"""
inputListLength = len(inputList)
if inputListLength == 0 or inputListLength == 1:
return inputList
"""If the list size is greater than 1, recursively break
it into 2 pieces and we will hit the base case of 1.
We then start merging upwards"""
return merge(merge_sort(inputList[:inputListLength//2]),
merge_sort(inputList[inputListLength//2:]))
"""Takes 2 sorted lists and combines them together to
return 1 sorted list"""
def merge(l1,l2):
l1Index = 0
l2Index = 0
#If either list is empty return the other
if len(l1) == 0:
return l2
if len(l2) == 0:
return l1
mergedSortedList = []
while True:
if l1[l1Index] <= l2[l2Index]:
mergedSortedList.append(l1[l1Index])
l1Index += 1
elif l2[l2Index] < l1[l1Index]:
mergedSortedList.append(l2[l2Index])
l2Index += 1
if not (l1Index < len(l1)):
mergedSortedList.extend(l2[l2Index:])
return mergedSortedList
elif not (l2Index < len(l2)):
mergedSortedList.extend(l1[l1Index:])
return mergedSortedList
print len(l1), l1Index, len(l2), l2Index
| true |
7fd5693cd6e035bb230eb535f4d9b0b0a5ce23bf | israel-dryer/Just-for-Fun | /mad_libs.py | 2,489 | 4.125 | 4 | # create a mad-libs | random story generator
# randomly select words to create a unique mad-libs story
from random import randint
import copy
# create a dictionary of the words of the type you will use in the story
word_dict = {
'adjective':['greedy','abrasive','grubby','groovy','rich','harsh','tasty','slow'],
'city name':['Chicago','New York','Charlotte','Indianapolis','Louisville','Denver'],
'noun':['people','map','music','dog','hamster','ball','hotdog','salad'],
'action verb':['run','fall','crawl','scurry','cry','watch','swim','jump','bounce'],
'sports noun':['ball','mit','puck','uniform','helmet','scoreboard','player'],
'place':['park','desert','forest','store','restaurant','waterfall']
}
# create a story and insert placeholders for the words you want to randomly select
story = (
"One day my {} friend and I decided to go to the {} game in {}. " +
"We really wanted to see the {} play the {}. " +
"So, we {} our {} down to the {} and bought some {}s. " +
"We got into the game and it was a lot of fun. " +
"We ate some {} {} and drank some {} {}. " +
"We had a great time! We plan to go ahead next year!"
)
# create a function that will randomly select a word from the word_dict by type of word
def get_word(type, local_dict):
''' select words based on type and then pop the selected word from the list
so that it isn't select more than once '''
words = local_dict[type]
cnt = len(words)-1 # used to set range of index
index = randint(0, cnt)
return local_dict[type].pop(index)
# create a function that will insert a random word into the story, based on word type
def create_story():
''' create a story with randomly selected words of certain type '''
local_dict = copy.deepcopy(word_dict) # deepcopy to prevent changes to word_dict
return story.format(
get_word('adjective', local_dict),
get_word('sports noun', local_dict),
get_word('city name', local_dict),
get_word('noun', local_dict),
get_word('noun', local_dict),
get_word('action verb', local_dict),
get_word('noun', local_dict),
get_word('place', local_dict),
get_word('noun', local_dict),
get_word('adjective', local_dict),
get_word('noun', local_dict),
get_word('adjective', local_dict),
get_word('noun', local_dict)
)
print("STORY 1: ")
print(create_story())
print()
print("STORY 2:")
print(create_story())
| true |
37ae8644ebe355a829433e96a4b5cba4fa1e45af | realRichard/-offer | /chapterThree/robust/reverseLinkList/reverse_linkList.py | 1,847 | 4.28125 | 4 | '''
题目:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
'''
class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
class LinkedList(object):
def __init__(self):
self.header = None
def insert(self, node):
if self.header is None:
self.header = node
else:
current_node = self.header
while current_node.next is not None:
current_node = current_node.next
current_node.next = node
def reverse_linkList(head):
if not isinstance(head, Node):
raise TypeError
behind = head
current = None
front = None
if behind.next is not None:
current = behind.next
behind.next = None
if current.next is not None:
front = current.next
while front is not None:
# print('behind', behind)
# print('current', current)
# print('front', front)
current.next = behind
behind = current
current = front
front = front.next
# 这一步是需要的, 不然连不上
current.next = behind
return current
else:
current.next = behind
return current
else:
return behind
def test():
link = LinkedList()
print(link, link.header)
for i in range(4):
node = Node(i)
link.insert(node)
result = reverse_linkList(link.header)
print(result)
c_node = result
while c_node is not None:
print(c_node.value)
c_node = c_node.next
if __name__ == '__main__':
test() | false |
a40082b1f88aab52a9b47c2bf79fa85aafddce0e | ciceropzr/DesafiosPython | /numeros.py | 317 | 4.25 | 4 | x = int(input('Insira um número => '))
if x < 0 and x % -2 == -1:
print('Número negativo impar')
elif x < 0 and x % -2 == 0:
print(' Número negativo par')
elif x % 2 == 0 and x != 0:
print(' Número positivo par')
elif x == 0:
print('Zero é NULOOOOOOOO....')
else:
print('Número positivo impar') | false |
3dd09e91200b964ae1114bf6d655fcb9776816fd | EnricoFiasche/assignment1 | /scripts/target_server.py | 1,276 | 4.125 | 4 | #!/usr/bin/env python
import rospy
import random
from assignment1.srv import Target, TargetResponse
def random_target(request):
"""
Function that generates two random coordinates (x,y) given the range
(min,max)
Args:
request: The request of Target.srv
- minimum value of the random coordinate
- maximum value of the random coordinate
Returns:
Random point (x,y) between the minimum and maximum value
"""
# getting the target Response (target_x, target_y)
result = TargetResponse()
# choosing randomly the two coordinates of the target point
result.target_x = random.uniform(request.minimum, request.maximum)
result.target_y = random.uniform(request.minimum, request.maximum)
# display the random target
rospy.loginfo("Target position [%.2f,%.2f]",result.target_x,result.target_y)
return result
def main():
"""
Main function that init a node called target_server and create
a service called target, used to generate a random point
"""
rospy.init_node('target_server')
# create a service called target, type Target,
# using a function called random_target
s = rospy.Service('target',Target,random_target)
rospy.spin()
if __name__ == '__main__':
try:
main()
except rospy.ROSInterruptException:
pass
| true |
a3af77c55562a3c70c9b1ee570086bc941b9bbee | Sidhved/Data-Structures-And-Algorithms | /Python/DS/Trees.py | 1,731 | 4.375 | 4 | #Program to traverse given tree in pre-order, in-order and post-order fashion
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self, root):
self.root = TreeNode(root)
def inorderTraversal(self, node, path):
if node:
path = self.inorderTraversal(node.left, path)
path += str(node.val) + " "
path = self.inorderTraversal(node.right, path)
return path
def preorderTraversal(self, node, path):
if node:
path += str(node.val) + " "
path = self.preorderTraversal(node.left, path)
path = self.preorderTraversal(node.right, path)
return path
def postorderTraversal(self, node, path):
if node:
path = self.postorderTraversal(node.left, path)
path = self.postorderTraversal(node.right, path)
path += str(node.val) + " "
return path
'''lets construct a binary tree as shown below to understand with help of an example
1
/ \
2 3
/ \ / \
4 5 6 7
'''
if __name__ == "__main__":
tree = Tree(1)
tree.root.left = TreeNode(2)
tree.root.right = TreeNode(3)
tree.root.left.left = TreeNode(4)
tree.root.left.right = TreeNode(5)
tree.root.right.left = TreeNode(6)
tree.root.right.left = TreeNode(7)
#In-Order Traversal : left -> root -> right
print(tree.inorderTraversal(tree.root, " "))
#Pre-order Traversal : root -> left -> right
print(tree.preorderTraversal(tree.root, " "))
#Post-order Traversal : left -> right -> root
print(tree.postorderTraversal(tree.root, " ")) | true |
c6899d11bbf0892f42b3b877bbe5f9a2a66bf757 | ben-coxon/cs01 | /sudoku_solver.py | 2,916 | 4.28125 | 4 | #!/usr/bin/python
# THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.
# A valid sudoku square satisfies these
# two properties:
# 1. Each column of the square contains
# each of the whole numbers from 1 to n exactly once.
# 2. Each row of the square contains each
# of the whole numbers from 1 to n exactly once.
# You may assume the the input is square and contains at
# least one row and column.
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
def check_sudoku(sud):
size = len(sud[0])
comp = []
lst = 0
a = 1
# Create list of numbers to check for
for n in sud[0]:
comp.append(a)
a += 1
# Create Vertical Numbers List
vert_list = []
n = 0
while n < size:
clist = []
for i in sud:
clist.append(i[n])
vert_list.append(clist)
n += 1
# Check horizontal numbers
while lst < size:
for i in comp:
if not i in sud[lst]:
print "\nhorizontal Fail!"
return False
lst += 1
# Check Vertical Numbers
lst = 0
while lst < size:
for i in comp:
if not i in vert_list[lst]:
print "\nvertical Fail!"
return False
lst += 1
print "\nThat's Sudoku!"
return True
### HERE IS THE SOLUTION FROM UDACITY, which is MUCH better!!!
def check_sudoku(p):
n = len(p) #extract size of grid
digit = 1 # start with 1
while digit <= n: # go through each digit
i = 0
while i < n: # go through each row and column
row_count = 0
col_count = 0
j = 0
while j < n: #for each entry in ith row/column
if p[i][j] == digit:
row_count += 1
if p[j][i] == digit:
col_count += 1
j += 1
if row_count != 1 or col_count != 1:
return False
i += 1 # next row/column
digit += 1 # next digit
return True # Sudoku was correct!
| true |
5421ce966d6b60ec40f9e43ece33809fe9576c84 | Ricky842/Shorts | /Movies.py | 1,404 | 4.40625 | 4 | #Empty list and dictionaries to store data for the movies and their ratings
movies = []
movie_dict = {'movie': '', 'rating': 0}
#Check validity of movie rating
def check_entry(rating):
while rating.isnumeric() is True:
movie_rating = int(rating)
if(movie_rating > 10 or movie_rating < 1):
rating = input("Please enter a rating between 1 and 10: ")
movie_rating = rating
else:
return movie_rating
movie_rating = input("Please enter an Integer between 1 and 10: ")
movie_rating = check_entry(movie_rating)
return movie_rating
#Calculates the highest rated movie
def rating():
numMovies = int(input("How many movies have you watched this year? "))
while len(movies) < numMovies:
movie_name = input("Please enter the name of the movie: ")
movie_rating = input(f"Please enter the rating of {movie_name} between 1 and 10: ")
movie_rating = check_entry(movie_rating)
movie_rating = int(movie_rating)
movie_dict = {'movie': movie_name, 'rating':movie_rating}
movies.append(movie_dict)
highest_rating = 0
for movie in movies:
if movie['rating'] > highest_rating:
highest_rating = movie['rating']
favMovie = movie['movie']
print(f"Your favorite movie was {favMovie} with a rating of {highest_rating}")
rating()
#Initial commit to Git | true |
5ed55cdbe3082ebcd87c8cc5ab40defff9542932 | anandavelum/RestApiCourse | /RestfulFlaskSection5/createdb.py | 605 | 4.125 | 4 | import sqlite3
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
cursor.execute("create table if not exists users (id INTEGER PRIMARY KEY,name text,password text)")
users = [(1, "Anand", "Anand"), (2, "Ramya", "Ramya")]
cursor.executemany("insert into users values (?,?,?)", users)
rows = list(cursor.execute("select * from users"))
print(rows)
connection.commit()
connection.close()
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
cursor.execute("Create table if not exists items(item_name primary key,price real)")
connection.commit()
connection.close() | true |
72994802e57e471f8cc14515072749eb35d79037 | LadyKerr/cs-guided-project-array-string-manipulation | /src/class.py | 657 | 4.21875 | 4 | # Immutable variables: ints; O(1) [to find new location for them is cheap]; string
# num = 1
# print(id(num))
# num = 100
# print(id(num))
# num2 = num
# print(num2 is num)
# num2 = 2
# print(num)
# print(num2 is num)
# Mutable Variables: arrays, dictionaries, class instances
arr = [1,2,3] #arrays are mutable
print(id(arr))
arr2 = arr
print(arr2 is arr)
arr2 = ['a', 'b'] # now assigning arr2 to something so this is a new array
print(arr)
arr2.append(4)
print(arr) # will return the original arr since arr2 was reassigned
# Mutable - Dictionaries
my_dict = {'hello': 'world'}
my_dict2 = my_dict
my_dict2['new_key'] = 'new value'
print(my_dict)
| true |
8c902651f21a4c5d25b384a3f73922c06eba74aa | gabefreedman/music-rec | /dates.py | 2,624 | 4.4375 | 4 | #!/usr/bin/env python
"""This module defines functions for manipulating and formatting date
and datetime objects.
"""
from datetime import timedelta
def get_month(today):
"""Format datetime to string variable of month name.
Takes in `today` and extracts the full month
name. The name is returned in all lowercase so
as to match the name of the URL.
Parameters
----------
today : datetime object
Returns
-------
month : str
Full name month extracted from datetime input.
"""
month = today.strftime('%B').lower()
return month
def get_previous_month(today):
"""Get full name of last month given datetime object.
Takes in `today` and finds the date of the last
day of the previous month. Formatted so as to
match the URL.
Parameters
----------
today : datetime object
Returns
-------
prev_month : str
Full name of last month extracted from datetime
input.
"""
first_of_month = today.replace(day=1)
prev = first_of_month - timedelta(days=1)
prev_month = prev.strftime('%B').lower()
return prev_month
def get_recent_monday(today):
"""Find the date of the nearest Monday.
Takes in `today` and and extracts the full month
name. The name is returned in all lowercase so
as to match the name of the URL.
Parameters
----------
today : datetime object
Returns
-------
recent_monday : date object
Date of nearest Monday to input datetime
"""
days_ahead = today.weekday()
if today.weekday() == 0:
recent_monday = today
elif today.weekday() <= 4:
recent_monday = today - timedelta(days=days_ahead)
else:
days_behind = 7 - days_ahead
recent_monday = today + timedelta(days=days_behind)
return recent_monday
def get_last_week_dates(today):
"""Retrieve the dates of the past 8 days.
Generates a list of dates in {month#}/{year#}
format from the past Monday to nearest Monday, inclusive.
Merges with full month name to form tuples.
Parameters
----------
today : datetime object
Returns
-------
full_week : list of 2-tuples
2-tuple of the form: (weekdate, full month name)
"""
week_end = get_recent_monday(today)
week_start = week_end - timedelta(days=7)
week_dates = [week_start + timedelta(days=i) for i in range(8)]
week_dates_fmt = [day.strftime('%#m/%#d') for day in week_dates]
months = [get_month(day) for day in week_dates]
full_week = list(zip(week_dates_fmt, months))
return full_week
| true |
3b2d9f12bcfee600b30eeb27e34788ae5c8ed4f9 | jc345932/sp53 | /workshopP1/shippingCalculator.py | 368 | 4.1875 | 4 | item =int(input("How many items:"))
while item < 0:
print("Invalid number of items!")
item = int(input("How many items:"))
cost =int(input("How much for item:"))
while cost < 0:
print("Invalid prices")
cost = int(input("How much for item:"))
total = cost * item
if total > 100:
total = total * 0.9
else:
total = total
print("Total is:$", total) | true |
1f45bdd57c3e4381ff05c668fadcb38bcaf589f8 | jc345932/sp53 | /workshopP4/numList.py | 322 | 4.15625 | 4 | list = []
for i in range(5):
num = int(input("Enter the number: "))
list.append(num)
print("The first number is: ",list[0])
print("the last number is: ", list[-1])
print("the smallest number is: ", min(list))
print("the largest number is: ",max(list))
print("the average of the numbers is: ",sum(list)/len(list))
| true |
c7443b333e6f8b64ca5e5d55c3cdaf0b64c8e291 | Necrolord/LPI-Course-Homework-Python-Homework- | /Exercise2-2.py | 1,123 | 4.53125 | 5 | #!/bin/usr/env python3.6
# This method is for reading the strings
def Input_Str():
x = str(input("Enter a String: "))
return x
# This method is for reading the number.
def Input_Num():
num = int(input("Enter a number between 1 and 3 included: "))
if ((num < 1) or (num > 3)):
print('The number you entered is not valid. Please enter another one.')
else:
return num
# This method comapres the length of the 2 strings.
def Compare_Str(str1,str2):
if len(str1) > len(str2):
print('The string ' , str1, 'Contains more letters than', str2)
elif len(2) > len(strr1):
print('The string' , str2, 'Contains more letters than', str1)
else:
print('Both strings contain the same amount of letters')
# This method is for checking if one string is inside the other string.
def Check_Str(str1,str2):
if str1 in str2:
print(str1, 'is inside' ,str2)
elif str2 in str1:
print(str2, 'is inside' ,str1)
else:
print(z, 'not inside at all', y)
num=Input_Num()
str1=Input_Str()
str2=Input_Str()
Compare_Str(str1,str2)
Check_Str(str1,str2)
| true |
23c4b91775a740a59ad4970b20935d3cfb50e768 | shafaypro/AndreBourque | /assignment1/mood2.py | 2,454 | 4.53125 | 5 | mood = input('Enter the mood of yours (angry,sad,happy,excited)') # we are taking an input in the form of a string
"""
if mood == "angry": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
if mood == "happy": # ANGRY
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
if mood == "sad":
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
if mood == "excited":
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
"""
# if else statment used for multiple checking ---> (nested if-else condition)
if mood == "angry": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
else: # if the mood is not angry
if mood == "sad": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
else: # if the mood is not angry and the mood is not sad
if mood == "happy": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry)
else: # if the mood is not angry nor the mood is sad nor the mood is happy -->
if mood == "excited": # check the value of the variable mood if the value is angry compares that with angry
print("Your %s" % mood) # the variable mood value is then replaced in the place of %s
print("Your mood is %s" % mood) # using the replacement operator (string %s <-- mood(angry) | true |
30db7f2a89d91bdd140df331d0b039d896803ee1 | franciscomunoz/pyAlgoBook | /chap4-Recursion/C-4.19.py | 1,890 | 4.4375 | 4 | """Function that places even numbers before odd
if returns are removed in the else condition, the recursion
tree becomes messy as shown :
(0, 6, [2, 3, 5, 7, 9, 4, 8])
(1, 6, [2, 3, 5, 7, 9, 4, 8])
(2, 5, [2, 8, 5, 7, 9, 4, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(2, 5, [2, 8, 4, 7, 9, 5, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
(1, 5, [2, 8, 4, 7, 9, 5, 3])
(2, 4, [2, 8, 4, 7, 9, 5, 3])
(3, 3, [2, 8, 4, 7, 9, 5, 3])
(4, 2, [2, 8, 4, 7, 9, 5, 3])
[2, 8, 4, 7, 9, 5, 3]
with the return statements in place gives a shorter recursion tree
(0, 6, [2, 3, 5, 7, 9, 4, 8])
(1, 6, [2, 3, 5, 7, 9, 4, 8])
(2, 5, [2, 8, 5, 7, 9, 4, 3])
(3, 4, [2, 8, 4, 7, 9, 5, 3])
(4, 3, [2, 8, 4, 7, 9, 5, 3])
[2, 8, 4, 7, 9, 5, 3]
"""
def move_even_odd(data,start,stop):
#print(start,stop,data)
if start > stop:
return
else:
if data[start] % 2 == 1 and data[stop] % 2 == 0:
data[start],data[stop] = data[stop],data[start]
move_even_odd(data,start+1,stop-1)
return
if data[start] % 2 == 0 and data[stop] % 2 == 0:
move_even_odd(data,start+1,stop)
return
if data[start] % 2 == 1 and data[stop] % 2 == 1:
move_even_odd(data,start,stop-1)
return
move_even_odd(data,start+1,stop-1)
if __name__ == '__main__':
tests=[]
tests.append([2,3,5,7,9,4,8])
tests.append([0,0,0,0,0,0,0])
tests.append([2,2,2,2,2,2,2])
tests.append([3,3,3,3,3,3,3])
tests.append([9,8,7,6,5,4,3,2,1])
tests.append([0,1,2,3,4,5,6,7,8,9])
tests.append([1,1,1,3,4,5,6,9,9,9])
for i in range(len(tests)):
move_even_odd(tests[i],0,len(tests[i])-1)
print(tests[i])
| true |
7981d8de44f4d1aaaab8aec30ea50b9fb1a87c48 | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/C-5.13.py | 1,095 | 4.125 | 4 | """The output illustrates how the list capacity is changing
during append operations. The key of this exercise is to
observe how the capacity changes when inserting data to an
an array that doesn't start at growing from size "0". We
use two arrays, the original from 5.1 and another starting
to grow from a different value. Both arrays grow by the same
values
"""
import sys # provides getsizeof function
if __name__ == '__main__':
try:
n = int(sys.argv[1])
except:
n = 100
initial_size = 1000
data = []
data_init_size = [] * initial_size
for k in range(n):
a = len(data)
b = sys.getsizeof(data)
a_l = len(data_init_size) + initial_size
b_l = sys.getsizeof(data_init_size)
print("Reference : Length: {0:3d}; Size in bytes: {1:4d}" \
" | | | Measured Array {2:3d}+ Length: {3:3d}; Size in bytes: {4:4d}:"\
.format(a,b,initial_size,a_l,b_l))
data_init_size.append(None)
data.append(None) # increase length by one
| true |
efd406bd5d1378e7d1d38e2329d5039fdd069730 | franciscomunoz/pyAlgoBook | /chap5-Array-Based_Sequences/P-5.35.py | 2,019 | 4.25 | 4 | """Implement a class , Substitution Cipher, with a constructor that takes a string
with 26 uppercase letters in an arbitrary order and uses that for the forward
mapping for encryption (akin to the self._forward string in our Caesar Cipher
class ) you should derive the backward mapping from the forward version"""
import string
from random import shuffle
class SubstitutionCipher:
"""Class for doing encryption and decryption using a Caesar cipher."""
def __init__(self, forward):
"""Construct Caesar cipher by calculating the decoder when encoder is given"""
decoder = [None] * 26
self._forward = (''.join(forward)) # will store as string
for i in range(len(forward)):
i_decoder = ord(forward[i]) - ord('A')
decoder[i_decoder] = chr( i + ord('A'))
self._backward = (''.join(decoder))
def encrypt(self, message):
"""Return string representing encripted message."""
return self._transform(message, self._forward)
def decrypt(self, secret):
"""Return decrypted message given encrypted secret."""
return self._transform(secret, self._backward)
def _transform(self, original, code):
"""Utility to perform transformation based on given code string."""
msg = list(original)
for k in range(len(msg)):
if msg[k].isupper():
j = ord(msg[k]) - ord('A') # index from 0 to 25
msg[k] = code[j] # replace this character
return ''.join(msg)
if __name__ == '__main__':
alpha_list = list(string.ascii_uppercase)
shuffle(alpha_list)
"""The encoding is donde using a random permutation of the alphabet and the
decoding array is calulated in the class ctor"""
cipher = SubstitutionCipher(alpha_list)
message = "THE Eagle IS IN PLAY; MEET AT JOE'S."
coded = cipher.encrypt(message)
print('Secret: ', coded)
answer = cipher.decrypt(coded)
print('Message:', answer)
| true |
7ed258a07a00f7092741efd7b9cef6dc69cdc4b8 | Marlon-Poddalgoda/ICS3U-Unit3-06-Python | /guessing_game.py | 980 | 4.25 | 4 | #!/usr/bin/env python3
# Created by Marlon Poddalgoda
# Created on December 2020
# This program is an updated guessing game
import random
def main():
# this function compares an integer to a random number
print("Today we will play a guessing game.")
# random number generation
random_number = random.randint(0, 9)
# input
user_guess = input("Enter a number between 0-9: ")
print("")
# process
try:
user_guess_int = int(user_guess)
if user_guess_int == random_number:
# output
print("Correct! {} was the right answer."
.format(random_number))
else:
# output
print("Incorrect, {} was the right answer."
.format(random_number))
except Exception:
# output
print("That's not a number! Try again.")
finally:
# output
print("")
print("Thanks for playing!")
if __name__ == "__main__":
main()
| true |
b9862bf717d958e138ffeb6918d21f5fe164a780 | Lutshke/Python-Tutorial | /variables.py | 882 | 4.40625 | 4 | "This is where i will show you the basics ok?"
# to add comments to code you need to start with a hashtag like i did
# there are a few types of numbers
# there are "ints" and "floats"
# an int is a full number (10, 45, 100..)
# an float is (0.1, 1,5...)
# an int or float are variables so they save values
int1 = 1
float1 = 1.5
# to save text you use strings
# a string needs to be between " " or ' '
string1 = "This is an example"
# to save a value which is true or false we use booleans (bool)
bool1 = True
bool2 = False
# to store a lot of items in 1 variable we use lists, dicts or tuples
# but nobody i know uses tuples
List1 = ["String1", "String2"]
Dict1 = {"name" : "paul", "lastname" : "peters"} # be sure to use the right symboles
# you can also save multiple dicts in a list
"those are the basic datatypes of python"
| true |
29e0c4f9290740a84e9f4125d8afec22aab9b3fa | Vlop01/Exercicios-Python-2 | /Desafio_65.py | 981 | 4.25 | 4 | #Crie um programa que leia vários números inteiros pelo teclado. No final de cada execução, mostre a média entre
#todos os valores e qual foi o maior e menor valor lido. O programa deve perguntar ao usuário se ele quer ou não
#continuar a digitar valores
continuar = 'sim'
count = 0
sum = 0
while continuar == 'sim' or continuar == 'Sim' or continuar == 'SIM' or continuar =='S' or continuar == 's':
num = int(input('Informe um número: '))
continuar = input('Deseja continuar[S/N]? ')
if count == 0:
greatest = num
smallest = num
else:
if num > greatest:
greatest = num
if num < smallest:
smallest = num
count += 1
sum = sum + num
if count > 0:
average = sum / count
else:
average = 'None'
print('A média entre os números é: {}'.format(average))
print('O maior número é: {}'.format(greatest))
print('O menor número é: {}'.format((smallest))) | false |
c1d8997d5fe31c5dda44c87cbbb1fd54512b74f0 | alecmchiu/DailyProgrammer | /e3.py | 820 | 4.125 | 4 | #!/Users/Alec/anaconda/bin/python
# Challenge E3
# https://www.reddit.com/r/dailyprogrammer/comments/pkw2m/2112012_challenge_3_easy/
def encrypt(text):
characters = list(text)
#new_chars = [chr(((ord(x)+824)%95)+32) for x in characters]
new_chars = []
for each in characters:
new = ord(each)+22
if (new < 127):
new_chars.append(chr(new))
else:
new=(new%127)+32
new_chars.append(chr(new))
encrypted = ''.join(new_chars)
return encrypted
def decrypt(text):
characters = list(text)
new_chars = []
for each in characters:
new = ord(each)
if (new < 54):
new = (new-32)+127
new=new-22
new_chars.append(chr(new))
decrypted = ''.join(new_chars)
return decrypted
if __name__=='__main__':
text = 'I am not a couch potato! I am a full potato!'
e = encrypt(text)
print e
print decrypt(e) | false |
11357e97c21e3e5b00d83a576959ca9fd32d9142 | DtjiSoftwareDeveloper/Python-Recursion-Tutorial | /recursive_fibonacci.py | 405 | 4.28125 | 4 | """
This file contains implementation of recursively calculating the nth Fibonacci number.
Author: DtjiSoftwareDeveloper
"""
def fibonacci(n: int) -> int:
if n == 0 or n == 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(2)) # 1
print(fibonacci(3)) # 2
print(fibonacci(4)) # 3
print(fibonacci(5)) # 5
print(fibonacci(6)) # 8
| false |
231d905f24fa551c060748793eee07c9ce563edd | deepaparangi80/Github_pycode | /sum_numb.py | 254 | 4.21875 | 4 | # program to print sum of 1 to n
n = int(input('Enter n value'))
print('entered value',n)
sum = 0
for i in range(1,n+1):
'''print(i)'''
sum = sum + i
print('total sum of 1 to {} is {}'.format(n,sum))
'''print (range(1,n))''' | true |
d778b446a64b2a12c3cd521aa611ca71937d2381 | JYDP02/DSA_Notebook | /Searching/python/breadth_first_search.py | 1,263 | 4.40625 | 4 | # Python3 Program to print BFS traversal
from collections import defaultdict
class Graph:
# Constructor
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (len(self.graph))
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print(s, end=" ")
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
# Create a graph
grph = Graph()
grph.addEdge(0, 1)
grph.addEdge(0, 2)
grph.addEdge(1, 2)
grph.addEdge(2, 0)
grph.addEdge(2, 3)
grph.addEdge(3, 3)
print("Following is Breadth First Traversal"
" (starting from vertex 2)")
grph.BFS(2) | true |
8bf11d623899a8640bd99dc352518a2c562c9e87 | lingaraj281/Lingaraj_task2 | /q3.py | 317 | 4.15625 | 4 | print("Enter a text")
a=str(input())
letter = input("Enter a letter\n")
letter_count = 0
for x in a:
if x == letter:
letter_count = letter_count + 1
num_of_letters = 0
for x in a:
if(x != " "):
num_of_letters = num_of_letters + 1
frequency = (letter_count/num_of_letters)*100
print(frequency) | true |
2e7266efc9d0d28413d9b28053d49830f6c85834 | JatinR05/Python-3-basics-series | /17. appending to a file.py | 864 | 4.40625 | 4 | '''
Alright, so now we get to appending a file in python. I will just state again
that writing will clear the file and write to it just the data you specify in
the write operation. Appending will simply take what was already there, and add
to it.
That said, when you actually go to add to the file, you will still use
.write... you only specify that you will be appending instead of writing
when you open the file and specify your intentions.
'''
# so here, generally it can be a good idea to start with a newline, since
# otherwise it will append data on the same line as the file left off.
# you might want that, but I'll use a new line.
# another option used is to first append just a simple newline
# then append what you want.
appendMe = '\nNew bit of information'
appendFile = open('exampleFile.txt','a')
appendFile.write(appendMe)
appendFile.close()
| true |
a429e619657d092618f27c24cd0a30abfbda9e3c | JatinR05/Python-3-basics-series | /9. if elif else.py | 972 | 4.34375 | 4 | '''
What is going on everyone welcome to my if elif else tutorial video.
The idea of this is to add yet another layer of logic to the pre-existing if else statement.
See with our typical if else statment, the if will be checked for sure, and the
else will only run if the if fails... but then what if you want to check multiple ifs?
You could just write them all in, though this is somewhat improper. If you actually desire to check every single if statement, then this is fine.
There is nothing wrong with writing multiple ifs... if they are necessary to run, otherwise you shouldn't really do this.
Instead, you can use what is called the "elif" here in python... which is short for "else if"
'''
x = 5
y = 10
z = 22
# first run the default like this, then
# change the x > y to x < y...
# then change both of these to an ==
if x > y:
print('x is greater than y')
elif x < z:
print('x is less than z')
else:
print('if and elif never ran...')
| true |
4ea711632c6a2bab41d0810384552a220d35eb7a | joe-bollinger/python-projects | /tip_calculator/tip_calculator.py | 1,703 | 4.25 | 4 | print('Tip Calculator')
print()
# TODO: Get the cost of the meal and print the results
get_cost = input('How much did your meal cost? (i.e. 45.67) ')
# Convert the input string to a float
get_cost = float(get_cost)
print(f"Food Cost: ${format(get_cost, '.2f')}")
# TODO: Calculate 10% sales tax for the bill and print the results.
def calc_tax():
return round(get_cost * 1.10, 2)
print(f"Your bill after tax: ${format(calc_tax(), '.2f')}")
print()
# TODO: Get the amount the customer would like to pay for a tip and print the results.
get_tip = input(
'What percentage of the bill would you like to pay as a tip? Please type in a number (i.e. 15) ')
# Convert the input string to a float.
get_tip = float(get_tip)
print(f'Customer wants to tip: {get_tip}%')
# TODO: Calculate the tip amount and print the results.
def calc_tip(tip):
if tip <= 0:
tip = 0
return round(get_cost * ((tip / 100)), 2)
else:
return round(get_cost * ((tip / 100)), 2)
print(f'Tip amount: ${calc_tip(get_tip)}')
def total_amount():
return calc_tip(get_tip) + calc_tax()
print(f'Total cost after tax and tip: ${total_amount()}')
print()
# TODO: Get number of people splitting the bill
get_diners = input('How many people will be splitting the bill? (i.e. 4) ')
# Convert the input string to a integer
get_diners = int(get_diners)
print('Diners:', get_diners)
# TODO: Calculate how much each person should pay (you can assume all people will split the bill evenly)
def split_amount(amount):
if amount <= 0:
amount = 1
return round(total_amount() / amount, 2)
print()
print(f"Each person should pay: ${format(split_amount(get_diners), '.2f')}")
| true |
f6717518f0fc59f794607f32ae3b2c33f8f88356 | sohel2178/Crawler | /file_test.py | 1,983 | 4.15625 | 4 |
# f= open('test.txt','r')
# print(f.mode)
# f.close()
# Context Manager
# with open('test.txt','r') as f:
# Read all the Content
# f_content = f.read()
# There is another method to read a file line by line
# f_content = f.readlines()
# print(f_content)
# Another way to read All of the Lines. Better Method then Above
# for line in f:
# print(line,end='')
# More Control Method to Read File
# if we pass 100 as an argument then it read 100 character from the file
# f_content = f.read(20)
# print(f_content,end='')
# f_content = f.read(20)
# print(f_content,end='')
# f_content = f.read(20)
# print(f_content,end='')
# size_to_read = 20
# f_content = f.read(size_to_read)
# If we reached the end of the file length of the f_content will be zero
# while len(f_content)>0:
# print(f_content,end='***')
# # print(f.tell())
# # print(f.seek())
# f_content = f.read(size_to_read)
# !!!! Wrinting a File !!!
# with open('test2.txt','w') as f:
# f.write('Hey Sohel How Are You')
# f.seek(0)
# f.write('Hey Sohel How Are You')
# f.seek(0)
# f.write('Hey Sohel How Are You')
# f.seek(0)
# !!! Copying Content of a File !!!
# with open('test.txt','r') as fr:
# with open('test_copy.txt','w') as fw:
# for line in fr:
# fw.write(line)
# !!! Copying Image File !!!
# with open('mobi.png','rb') as fr:
# with open('mobi_copy.png','wb') as fw:
# for line in fr:
# print(line)
# !!! Print Binary File and Examine !!!
# with open('mobi.png','rb') as fr:
# print(fr.read())
# !!! Read and Write Chunk by Chunk !!!
with open('mobi.png','rb') as fr:
chunk_size = 4096
with open('mobi_copy.png','wb') as fw:
chunk_data = fr.read(chunk_size)
while len(chunk_data) > 0:
fw.write(chunk_data)
chunk_data = fr.read(chunk_size)
| true |
d05f46251c0c3550dd70cda5948587aaf72d4901 | Kjeldgaard/ProjectEuler | /src/multiple_3_5.py | 1,326 | 4.15625 | 4 | #!/user/bin/env python3 -tt
"""
Multiples of 3 and 5
https://projecteuler.net/problem=1
"""
# Imports
import sys
import argparse
def sum_of_multiples(number :int, divisor :int) -> int:
max_multiple = int((number - 1) / divisor)
times_multiple = float((max_multiple + 1) / 2) * max_multiple
sum_of_multiples = int(divisor * times_multiple)
return sum_of_multiples
def main(number :int, divisor1 :int, divisor2 :int):
print(f"Number {number} and divisors {divisor1} and {divisor2}")
sum_multiples = sum_of_multiples(number, divisor1)
sum_multiples += sum_of_multiples(number, divisor2)
overlapping = sum_of_multiples(int(number / divisor1), divisor2) * divisor1
sum_multiples -= overlapping
print(f"Sum of multiples: {sum_multiples}")
return
# Main body
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('n',
type = int,
help = 'Number to find sum of dividers')
parser.add_argument('d1',
type = int,
help = 'Divisor 1.')
parser.add_argument('d2',
type = int,
help = 'Divisor 2.')
args = parser.parse_args()
main(args.n, args.d1, args.d2)
| false |
f7f83ae4a45bf1896a6c7d9608f9f560e8bf904f | ishan5886/Python-Learning | /OOPS Concepts/OOPS-Class Variables.py | 2,480 | 4.15625 | 4 | # class Employee:
# def __init__(self, first, last, pay):
# self.first = first
# self.last = last
# self.pay = pay
#
# def fullname(self):
# return '{} {}'.format(self.first, self.last)
#
# def appraise(self): #Without using class variable
# self.pay = int(self.pay * 1.04)
#
#
# emp_1 = Employee('Ishan', 'Dhaliwal', 90000)
# print(emp_1.pay)
# emp_1.appraise()
# print(emp_1.pay)
#------------------------------------------With Class Variable-----------------------------------------------------#
#
# class Employee:
#
# raise_amount = 2.50
#
# def __init__(self, first, last, pay):
# self.first = first
# self.last = last
# self.pay = pay
#
# def fullname(self):
# return '{} {}'.format(self.first, self.last)
#
# def appraise(self):
# self.pay = int(self.pay * Employee.raise_amount) # Access Class Variable through ClassName
# self.pay = int(self.pay * self.raise_amount) # Access Class Variable through Instance(self)
#
#
# emp_1 = Employee('Ishan', 'Dhaliwal', 90000)
# print(emp_1.pay)
# emp_1.appraise()
# print(emp_1.pay)
# #
# print(emp_1.raise_amount) #Access Class variable through Instance(Self)
# print(Employee.raise_amount) #Access Class Variable through classname
#
# # Employee.raise_amount = 3.00 #syntax to change class variable value
# #
# # print(Employee.raise_amount)
# # print(emp_1.raise_amount)
#
# emp_1.raise_amount = 4.00 #syntax to change instance variable value
#
# print(emp_1.raise_amount)
# print(Employee.raise_amount)
#---------------------------------------------------------------------------------------------------------------------#
#
# class Employee:
#
# emp_no = 0
# raise_amount = 2.50
#
# def __init__(self, first, last, pay):
# self.first = first
# self.last = last
# self.pay = pay
#
# Employee.emp_no += 1
#
# def fullname(self):
# return '{} {}'.format(self.first, self.last)
#
# def appraise(self):
# self.pay = int(self.pay * Employee.raise_amount) # Access Class Variable through ClassName
# self.pay = int(self.pay * self.raise_amount) # Access Class Variable through Instance(self)
#
#
# emp_1 = Employee('Ishan1', 'Dhaliwal1', 90000)
# emp_2 = Employee('Ishan2', 'Dhaliwal2', 10000)
# emp_3 = Employee('Ishan3', 'Dhaliwa3', 20000)
# emp_4 = Employee('Ishan4', 'Dhaliwal4', 30000)
#
# print(Employee.emp_no) | false |
80e00f4c0f308f8c361a884b08c56b60f3e6d4b3 | ishan5886/Python-Learning | /Decorators.py | 1,020 | 4.21875 | 4 | #Decorators - Function that takes function as an argument, performs some functionality and returns another function
# def outer_function(msg):
# def inner_function():
# print(msg)
# return inner_function
# def decorator_function(original_function):
# def wrapper_function():
# return original_function()
# return wrapper_function
#
# @decorator_function # Same as display = decorator_function(display)
#
# def display():
# print('Display function ran')
#
#
# display()
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function # Same as display = decorator_function(display)\
def display():
print('Display function ran')
@decorator_function # Same as display_args = decorator_function(display_args)\
def display_args(name, age):
print('Display function ran with arguments ({}, {})'.format(name, age))
display()
display_args('Ishan', 95) | true |
661627a12dc195ee9a2c9b26fc340d7e0a2099be | LavanyaBashyagaru/letsupgrade- | /day3assigment.py | 539 | 4.21875 | 4 | '''You all are pilots, you have to land a plane,
the altitude required for landing a plane is 1000ft,
if it is less than that tell pilot to land the plane,
or it is more than that but less than 5000 ft
ask the pilot to come down to 1000 ft,
else if it is more than 5000ft ask the pilot togo around and try later'''
altitude=int(input("ft:"))
if(altitude<=1000):
print("Land the plane")
elif(altitude>1000 and altitude<5000):
print("Come down to 1000ft")
elif(altitude>5000):
print("Go around and try later")
| true |
70d43485cecbf81e32017c8ebfde6720de099f9a | felipesantos10/Python | /mundoUM/aula8.py | 693 | 4.125 | 4 | #Utilizando módulos
#import math ( importando toda a biblioteca de matematica)
#from math import sin( importante apenas as informações que eu necessito da biblioteca)
#funcionalidades do match
#Funcionalidade do match
#ceil (arrendomamento pra cima)
#floor (arredodamento pra baixo)
#trunc ( quebrar o numero)
#pow (potencia)
#sqrt (raiz quadrada)
#factorial (calculo fatorial)
#Primeiro forma
import math
num = int(input('Digite um numero? '))
raiz = math.sqrt(num)
print('A raiz do numero {} é igual a {}'.format(num,raiz))
#Segunda forma
from math import sqrt
num = int(input('Digite um numero? '))
raiz = sqrt(num)
print('A raiz do numero {} é igual a {}'.format(num,raiz))
| false |
c61b8d10b26b658b8299c691de760b7ab6eb1249 | felipesantos10/Python | /mundoUM/ex022.py | 384 | 4.15625 | 4 | #Crie um programa que lei o nome completo de uma pessoa e mostre
#O nome com todas as letras em maisculas
#O nome com todas minusculas
#Quantas letras ao todo(sem considerar os espaços vazios)
#quantas letras tem o primeiro nome
nome = str(input('Digite o seu nome completo? ')).strip()
print(nome.upper())
print(nome.lower())
print(len(nome)-nome.count(' '))
print(nome.find(' '))
| false |
953b47f0be6a1c46f7c75b888dccf5d9e484f920 | MarsForever/python_kids | /7-1.py | 316 | 4.125 | 4 | num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 < num2:
print (num1, "is less than",num2)
if num1 > num2:
print (num2, "is more than",num2)
if num1 == num2:
print (num1,"is equal to",num2)
if num1 != num2:
print (num1,"is not equal to", num2)
| true |
69ab8d1b2593f44099b0514e9b824f070af324f2 | syurskyi/100DaysOfCode_i_Python | /01-03-datetimes/datetime_date.py | 667 | 4.25 | 4 | #!python3
from datetime import datetime
from datetime import date
datetime.today()
# datetime.datetime(2018, 2, 19, 14, 38, 52, 133483)
today = datetime.today()
print(type(today))
# <class 'datetime.datetime'>
todaydate = date.today()
print(todaydate)
# datetime.date(2018, 2, 19)
print(type(todaydate))
# <class 'datetime.date'>
print(todaydate.month)
# 2
print(todaydate.year)
# 2018
print(todaydate.day)
# 19
christmas = date(2018, 12, 25)
print(christmas)
# datetime.date(2018, 12, 25)
if christmas is not todaydate:
print("Sorry there are still " + str((christmas - todaydate).days) + " until Christmas!")
else:
print("Yay it's Christmas!") | false |
6461becb3ef2198b34feba0797459c22ec886e4c | OrSGar/Learning-Python | /FileIO/FileIO.py | 2,953 | 4.40625 | 4 | # Exercise 95
# In colts solution, he first read the contents of the first file with a with
# He the used another with and wrote to the new file
def copy(file1, file2):
"""
Copy contents of one file to another
:param file1: Path of file to be copied
:param file2: Path of destination file
"""
destination = open(file2, "w")
with open(file1, "r") as source:
destination.write(source.read())
destination.close()
# Exercise 96
# In Colts code, he didnt save the reverse - He just reversed it when we passed it in
def copy_and_reverse(file1, file2):
"""
Copy contents of a file to another in reverse
:param file1: Path of file ot be copied
:param file2: Path of destination file
"""
with open(file1, "r") as source:
data = source.read()
with open(file2, "w") as destination:
reverse_data = data[::-1]
destination.write(reverse_data)
# Exercise 97
def statistics_2(file):
"""
Print number of lines, words, and characters in a file
:param file: Path of file
"""
with open(file) as source:
lines = source.readlines()
return {"lines": len(lines),
"words": sum(len(line.split(" ")) for line in lines),
# Split every line on a space and count how many elements there are
"characters": sum(len(line) for line in lines)} # Count number of chars in each line
def statistics(file):
""" My original version of statistics_2 """
num_lines = 0
num_char = 0
num_words = 1
with open(file) as source:
line = source.readlines()
num_lines = len(line)
source.seek(0)
data = source.read()
num_char = len(data)
for char in data:
if char == " ":
num_words += 1
return {"lines": num_lines, "words": num_words, "characters": num_char}
# Exercise 98
# In Colts implementation, he just read the whole thing and replaced it
def find_and_replace(file, target, replacement):
"""
Find and replace a target word in a file
:param file: Path to the file
:param target: Word to be replaced
:param replacement: Replacement word
"""
with open(file, "r+") as source:
for line in source:
print(line)
if line == "":
break
elif line.replace(target, replacement) != line:
source.write(line.replace(target, replacement))
def f_n_r(file, target, replacement):
""" Another version of find_and_replace """
with open(file, "r+") as source:
text = file.read()
new_text = text.replace(target, replacement)
file.seek(0)
file.write(new_text)
file.truncate() # Delete everything after a certain position
find_and_replace("fileio.txt", "Orlando", "Ligma")
copy("fileio.txt", "fileio_copy.txt")
copy_and_reverse("fileio.txt", "fileio_copy.txt")
print(statistics_2("fileio.txt"))
| true |
60ce089cbbc612632e6e249227e3cac374e59ad1 | MNJetter/aly_python_study | /diceroller.py | 1,396 | 4.15625 | 4 | ##################################################
## Begin DICEROLLER. ##
##################################################
## This script is a d20-style dice roller. It ##
## requires the user to input numbers for a ##
## multiplier, dice type, and modifier, and ##
## displays relevant information on the screen, ##
## including the result of each roll. ##
##################################################
## (c) 2015 Aly Woolfrey ##
##################################################
import random
random.seed()
rollnums = []
def roll_the_dice(d_mult, d_type, d_mod):
print "Rolling %dd%d + %d." % (d_mult, d_type, d_mod)
while d_mult > 0:
rollnums.append(random.randint(1, d_type))
d_mult -= 1
totalroll = sum(rollnums)
print "Your raw rolls are: %s" % (rollnums)
print "Your total unmodified roll is: %d" % (totalroll)
print "Your final number is %d" % (totalroll + d_mod)
mult_num = int(raw_input("Input multiplier (_DX + X): "))
type_num = int(raw_input("Input dice type (XD_ + X): "))
mod_num = int(raw_input("Input your modifier. Type 0 if there is no modifier. (XDX + _): "))
roll_the_dice(mult_num, type_num, mod_num)
##################################################
## End DICEROLLER. ##
##################################################
| true |
a425af412c404ebbef4e634ce335c58b75b7cee1 | RhettWimmer/Scripting-for-Animation-and-Games-DGM-3670- | /Python Assignments/scripts(old)2/Calculator.py | 2,452 | 4.21875 | 4 | '''
Enter a list of values for the calculator to solve in "Values"
Enter a value in to "Power" to calculate the power of "Values"
Define "userInput" to tell the calculator what function to solve for.
1 = Add
2 = Subtract
3 = Multiply
4 = Divide
5 = Power
6 = Mean
7 = Median
8 = Mode
'''
import maya.cmds as mc
Values = [1,10,50,50,100]
Power = 3
class Calculator:
def __init__(self):
pass
# Addition input 1 #
def Add(self, Vals):
total = 0
for i in Vals:
total += i
print 'Adding ' + str(Values) + ' = '
print total
return total
# Subtraction input 2#
def Sub(self, Vals):
total = Vals[0]
for i in Vals[1:]:
total -= i
print 'Subtracting ' + str(Values) + ' = '
print total
return total
# Multiplication input 3 #
def Multi(self, Vals):
total = 1
for i in Vals:
total *= i
print 'Multiplying ' + str(Values) + ' = '
print total
return total
# Division input 4 #
def Divi(self, Vals):
total = Vals[0]
for i in Vals[1:]:
total /= i
print 'Dividing ' + str(Values) + ' = '
print total
return total
# Power input 5#
def Pow(self, Vals, PowerVal):
import math
print 'The powers of ' + str(Values) + " to the power of " + str(Power) + ' = '
for i in Vals:
print math.pow(i, PowerVal)
# Mean input 6 #
def Mean(self, Vals):
import statistics
total = Vals
print 'The mean of ' + str(Values) + ' = '
print statistics.mean(total)
return statistics.mean(total)
# Median input 7 #
def Median(self, Vals):
import statistics
total = Vals
print 'The median of ' + str(Values) + ' = '
print statistics.median(total)
return statistics.median(total)
# Mode input 8 #
def Mode(self, Vals):
import statistics
total = Vals
print 'The mode of ' + str(Values) + ' = '
print statistics.mode(total)
return statistics.mode(total)
calc = Calculator()
calc.Add(Values)
calc.Sub(Values)
calc.Multi(Values)
calc.Divi(Values)
calc.Pow(Values, Power)
calc.Mean(Values)
calc.Median(Values)
calc.Mode(Values) | true |
3a75c905a3831727c8152674d1daa3c81f2be4d0 | sharly2012/wechat-applet-test | /testcase/0001.py | 1,598 | 4.25 | 4 | def bubble_sort(array):
length = len(array)
if length < 2:
return array
else:
for i in range(length - 1):
for j in range(length - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
def quick_sort(array):
length = len(array)
if length < 2:
return array
else:
base_value = array[0]
small, equal, big = [], [base_value], []
for i in array[1:]:
if i > base_value:
big.append(i)
elif i < base_value:
small.append(i)
else:
equal.append(i)
return quick_sort(small) + equal + quick_sort(big)
def search_sort(array):
length = len(array)
if length < 2:
return array
else:
for i in range(length):
base_index = i
for j in range(i, length):
if array[j] < array[base_index]:
base_index = j
if base_index != i:
array[base_index], array[i] = array[i], array[base_index]
return array
def insert_sort(array):
length = len(array)
if length < 2:
return array
else:
for i in range(length):
for j in range(i, 0, -1):
if array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
return array
if __name__ == '__main__':
list_a = [1, 5, 9, 6, 4, 5, 10]
print(list_a)
list_b = insert_sort(list_a)
print(list_b)
| false |
db95ed4eccce222cea4b4326ab5e4586f2916ac3 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /17_mode/mode.py | 856 | 4.28125 | 4 | def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
2
"""
# mode_out will hold the number that occurred the most
mode_out = ""
# greatest_frequency will hold the largest total times a number occured.
greatest_frequency = 0
num_frequency = {num: 0 for num in nums}
for num in nums:
num_frequency[num] += 1
# did the amount of times num occur exceed the amount in greatest_frequency?
if (num_frequency[num] >= greatest_frequency):
# yes, we have a new most common number
mode_out = num
return mode_out
| true |
cce0a73b95333ca1cdb18857403a41ede3cdb6a4 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /12_multiply_even_numbers/multiply_even_numbers.py | 589 | 4.375 | 4 | def multiply_even_numbers(nums):
"""Multiply the even numbers.
>>> multiply_even_numbers([2, 3, 4, 5, 6])
48
>>> multiply_even_numbers([3, 4, 5])
4
If there are no even numbers, return 1.
>>> multiply_even_numbers([1, 3, 5])
1
If the list is empty, return 1.
>>> multiply_even_numbers([])
1
"""
evens_product_out = 1
nums_even = [num for num in nums if num % 2 == 0]
if (len(nums_even) > 0):
for num in nums_even:
evens_product_out *= num
return evens_product_out
| false |
f320f52b98025d0edfb543da612d28752ec6f579 | JimGeist/sb_18-02-20_Python_Data_Structures_Exercise | /06_single_letter_count/single_letter_count.py | 587 | 4.28125 | 4 | def single_letter_count(word, letter):
"""How many times does letter appear in word (case-insensitively)?
>>> single_letter_count('Hello World', 'h')
1
>>> single_letter_count('Hello World', 'z')
0
>>> single_letter_count("Hello World", 'l')
3
"""
# letter count via list comprehension
letter_lower = letter.lower()
word_lower = word.lower()
if (letter_lower in word_lower):
letter_list = [char for char in word_lower if char == letter_lower]
return len(letter_list)
else:
return 0
| false |
90707b2e54d15dcf7ecdcf4286a2409b271968a4 | ibrahimuslu/udacity-p0 | /Task4.py | 1,555 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
count =0
textPhoneDict = {}
callingPhoneDict = {}
receiveingPhoneDict = {}
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
for text in texts:
if text[0] not in textPhoneDict :
textPhoneDict[text[0]]=1
else:
textPhoneDict[text[0]]+=1
if text[1] not in textPhoneDict:
textPhoneDict[text[1]]=1
else:
textPhoneDict[text[1]]+=1
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
for call in calls:
if call[0] not in callingPhoneDict:
callingPhoneDict[call[0]]=1
else:
callingPhoneDict[call[0]]+=1
if call[1] not in receiveingPhoneDict:
receiveingPhoneDict[call[1]]=1
else:
receiveingPhoneDict[call[1]]+=1
print("These numbers could be telemarketers: ")
for phone in sorted(callingPhoneDict):
if phone not in receiveingPhoneDict and phone not in textPhoneDict:
print(phone)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
| true |
35c53757e5669ad24a4b61aa6878b722de8636e1 | martinee300/Python-Code-Martinee300 | /w3resource/Python Numpy/Qn3_PythonNumpy_CreateReshapeMatrix.py | 508 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 14:24:51 2018
@author: dsiow
"""
# =============================================================================
# 3. Create a 3x3 matrix with values ranging from 2 to 10.
# Expected Output:
# [[ 2 3 4]
# [ 5 6 7]
# [ 8 9 10]]
# =============================================================================
import numpy as np
listing = list(range(2,11))
# Use the reshape method to change it into a 3x3 matrix
array = np.array(listing).reshape(3,3)
| true |
cb0ae7e3a71550c42711351027a21917668560ba | robinrob/python | /practice/print_reverse.py | 441 | 4.125 | 4 | #!/usr/bin/env python
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def ReversePrint(head):
if head is not None:
if head.next is not None:
ReversePrint(head.next)
print head.data
head = Node(data=0)
one = Node(data=1)
head.next = one
two = Node(data=2)
one.next = two
three = Node(data=3)
two.next = three
ReversePrint(head) | true |
237a9ccbbfa346ff3956f90df5f52af4272b9291 | robinrob/python | /practice/postorder_traversal.py | 727 | 4.1875 | 4 | #!/usr/bin/env python
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)
"""
lr = Node(data=4)
ll = Node(data=1)
l = Node(data=5, left=ll, right=lr)
rl = Node(data=6)
r = Node(data=2, left=rl)
tree = Node(data=3, left=l, right=r)
import sys
def postOrder(root):
#Write your code here
node = root
if node.left is not None:
postOrder(node.left)
if node.right is not None:
postOrder(node.right)
sys.stdout.write(str(node.data) + ' ')
postOrder(tree) | true |
1c047ac76bcb2fa3e902d3f5b6e0e145cc866c5d | KyleLawson16/mis3640 | /session02/calc.py | 871 | 4.21875 | 4 | '''
Exercise 1
'''
import math
# 1.
radius = 5
volume = (4 / 3 * math.pi * (radius**3))
print(f'1. The volume of a sphere with radius {radius} is {round(volume, 2)} units cubed.')
# 2.
price = 24.95
discount = 0.4
copies = 60
cost = (price * discount) + 3 + (0.75 * (copies - 1))
print(f'2. The total wholesale cost of {copies} copies is ${round(cost, 2)}.')
# 3.
easy_pace = 8 + (15/60)
tempo = 7 + (12/60)
total_time = (easy_pace * 2) + (tempo * 3)
start_time_min = (6*60) + 52
end_time_min = start_time_min + total_time
end_time = '{hours}:{minutes}'.format(hours=(round(end_time_min // 60)), minutes=(round(end_time_min % 60)))
print(f'3. You will get home for breakfast at {end_time} am.')
# 4.
start = 82
end = 89
difference = end - start
percent_change = difference / start * 100
print('4. Your average grade rose by {:04.1f}%'.format(percent_change))
| true |
67cf1c78b300282078a2e00abafe7b8f81d4f837 | roshandcoo7/DSA | /Hashing/Hash_chaining.py | 723 | 4.25 | 4 | # Function to display hash table
def dispay(hashTable):
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()
# Creating hash table as a nested list
HashTable = [[] for _ in range(10)]
# Hash function
def Hash(keyValue):
return keyValue % len(HashTable)
# Insert function
def insert(hashTable, keyValue, Value):
hashKey = Hash(keyValue)
hashTable[hashKey].append(Value)
insert(HashTable,10,'calicut')
insert(HashTable,25,'Kannur')
insert(HashTable,20,'Kochi')
insert(HashTable,9,'Thalassery')
insert(HashTable,21,'Trivandrum')
insert(HashTable,21,'Trishur')
dispay(HashTable)
| false |
a505d2e7912bd22c14d95df0e29c7caec4e28ac4 | roshandcoo7/DSA | /Tree/BST.py | 2,578 | 4.125 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# INSERTING AN ELEMENT TO THE TREE
def insert(self, data):
if self.data is None:
self.data = data
else:
if self.data <= data:
if self.right:
self.right.insert(data)
else:
self.right = Node(data)
elif self.data > data:
if self.left:
self.left.insert(data)
else:
self.left = Node(data)
# !REMOVING AN ELEMENT FROM THE TREE
# def remove(self, data):
# if self.data:
# if self.data == data:
# if self.left and self.right:
# curr = self.right
# while curr.left is not None:
# curr = curr.left
# inOrderSuccessor = curr.data
# self.data,inOrderSuccessor = inOrderSuccessor,self.data
# self.right.remove(inOrderSuccessor)
# elif not self.left and not self.right:
# self.data = None
# else:
# if self.left and not self.right:
# self.data,self.left.data = self.left.data,self.data
# self.left.remove(data)
# elif self.right and not self.left:
# self.data,self.right.data = self.right.data,self.data
# self.right.remove(data)
# elif self.data <= data:
# self.right.remove(data)
# elif self.data > data:
# self.left.remove(data)
# TRAVERSING THE TREE
def inOrder(self):
if self.left:
self.left.inOrder()
print(self.data)
if self.right:
self.right.inOrder()
def preOrder(self):
print(self.data)
if self.left:
self.left.preOrder()
if self.right:
self.right.preOrder()
def postOrder(self):
if self.left:
self.left.postOrder()
if self.right:
self.right.postOrder()
print(self.data)
root = Node(50)
root.insert(30)
root.insert(70)
root.insert(20)
root.insert(40)
root.insert(60)
root.insert(80)
root.inOrder()
print('***************************')
root.remove(30)
root.inOrder()
# root.postOrder()
print('***************************')
root.preOrder() | false |
2edf1b59279ba88f504a800fc9faae1bcd71000d | jorgeortizc06/curso_python | /sets.py | 407 | 4.125 | 4 | #Set: es una coleccion que no esta ordenada ni indexada y se mete en llaves.
#Create an empty set
s = set()
#Add elements to set
s.add(1)
s.add(2)
s.add(3)
s.add(4)
s.add(3) #Los sets no admite valores repetidos. No se agrega a la cadena
print(s)
s.remove(2)
print(s)
#f me permite introducir parametros en println enter {}
#len devuelve el tamaño de la cadena
print(f"The set has {len(s)} elements.")
| false |
91b435e4c6afda99270bec91eae519bcb8a09cf8 | amolsmarathe/python_programs_and_solutions | /2-Basic_NextConceptsAndNumpy/4-LocalGlobalVariables.py | 1,522 | 4.40625 | 4 | # Local- defined inside the function
# Global- defined outside the function
# Global can always be accessed inside function, given that same variable is not defined inside function, however,
# local variable cannot be accessed outside the function
# Local and global variables are different
# 'global'-Global variable can be recalled inside a function using 'global' function - BUT with such usage, BOTH local &
# GLOBAL variables cannot exist inside a function at the same time. Changes are directly reflected on global
# variable from within the function
# 'globals' - function can be used when we need BOTH local as well as global variables to be accessed in function
# Local and global variables are different
a = 10
def fun():
a = 15
print('\n a inside function= ', a, 'with address= ', id(a))
fun()
print(' a outside function= ', a, 'with address= ', id(a))
# 'global'- Global variable can be recalled inside a function using global function:
a = 10
def fun():
global a
a = 15
print('\n a inside function= ', a, 'with address= ', id(a))
fun()
print(' a outside function= ', a, 'with address= ', id(a))
# 'globals'- Global as well as local variable can be accessed inside a function using globals function:
a = 10
def fun():
x = globals()['a']
a = 15
print('\n a inside function= ', a, 'with address= ', id(a))
print(' Value of global variable \'a\' accessed inside function is = ', x)
fun()
print(' a outside function= ', a, 'with address= ', id(a))
| true |
30a9464d99def27837a31aa58c3dc01a4e494ce6 | amolsmarathe/python_programs_and_solutions | /3-ObjectOriented/5-Polymorphism-3&4-MethodOverload&Override.py | 1,439 | 4.71875 | 5 | # Method Overload (within same class): 2 methods exist with same name but different number of args
# - NOT supported as it is in python,we CANNOT have 2methods with same name in python. But there is a similar concept
# - In python,we define method with arg=None &while creating an object,it will get default value None if arg is absent
# - This itself can be called as a similar concept to Method overload
# Method Override (within 2 diff. classes): 2 methods exist with same name and same no. of args but in different classes
# - When we inherit the classes i.e. class B(A) and both A and B have same methods, preference is given to
# - the method from class B over class A. This is called method override
# Method Overload Example:
class Addition:
def add(self, a=None, b=None, c=None):
sum = 0
if a != None and b != None and c != None:
sum = a + b + c
elif a != None and b != None:
sum = a + b
else:
sum = a
return sum
a1 = Addition()
print(a1.add(5, 6, 7)) # In this way, we have overloaded same method 'add' by passing different no. of args
print(a1.add(5, 6))
print(a1.add(5))
# Method Override Example:
class A:
def printfun(self):
print('Fun in Class A')
class B(A):
def printfun(self): # this method overrides the method in class A
print('Fun in Class B')
b1 = B()
b1.printfun()
| true |
6b7990e5343b9d1d270c6ce96391a63ca89a708c | v-v-d/algo_and_structures_python | /Lesson_1/3.py | 994 | 4.125 | 4 | # 3. По введенным пользователем координатам двух точек вывести
# уравнение прямой вида y = kx + b, проходящей через эти точки.
try:
x1 = float(input('Введите значение \'x\' первой точки: '))
y1 = float(input('Введите значение \'y\' первой точки: '))
x2 = float(input('Введите значение \'x\' второй точки: '))
y2 = float(input('Введите значение \'y\' второй точки: '))
if x1 == x2:
print(f'Уравнение прямой: x = {x1}')
else:
k = (y2-y1) / (x2-x1)
b = y1 - x1*k
if y1 == y2:
print(f'Уравнение прямой: y = {b}')
else:
print(f'Уравнение прямой: y = {k}x + {b}')
except ValueError:
print('Введенные значения должны быть числом')
| false |
6ae308c70df76a428172a9afa44fc0a4870e55ca | v-v-d/algo_and_structures_python | /Lesson_7/2.py | 1,348 | 4.34375 | 4 | """
2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
заданный случайными числами на промежутке [0; 50). Выведите на экран исходный
и отсортированный массивы.
"""
import random
def merge_sort(lst):
if len(lst) > 1:
center = len(lst) // 2
left = lst[:center]
right = lst[center:]
merge_sort(left)
merge_sort(right)
left_idx = right_idx = list_idx = 0
while left_idx < len(left) and right_idx < len(right):
if left[left_idx] < right[right_idx]:
lst[list_idx] = left[left_idx]
left_idx += 1
else:
lst[list_idx] = right[right_idx]
right_idx += 1
list_idx += 1
while left_idx < len(left):
lst[list_idx] = left[left_idx]
left_idx += 1
list_idx += 1
while right_idx < len(right):
lst[list_idx] = right[right_idx]
right_idx += 1
list_idx += 1
return lst
if __name__ == '__main__':
random_list = [round(random.uniform(0, 50), 2) for _ in range(27)]
print(random_list)
print(merge_sort(random_list))
| false |
516073604835fd28c8f1c6e3a63656d9e513efdb | v-v-d/algo_and_structures_python | /Lesson_2/4.py | 1,487 | 4.1875 | 4 | """
4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ...
Количество элементов (n) вводится с клавиатуры.
"""
# Рекурсия
def get_sum_of_series(num_of_elements, num=1, summ=0):
summ += num
num /= -2
num_of_elements -= 1
if num_of_elements:
return get_sum_of_series(num_of_elements, num, summ)
return summ
try:
num_of_elements = int(input('Введите кол-во элементов: '))
if num_of_elements > 0:
print(f'Сумма {num_of_elements} элементов ряда: {get_sum_of_series(num_of_elements)}')
else:
print('Ошибка! Необходимо ввести положительное целое число больше 0')
except ValueError:
print('Ошибка! Необходимо ввести целое число')
# Цикл
try:
num_of_elements = int(input('Введите кол-во элементов: '))
if num_of_elements > 0:
num = 1
summ = 0
for _ in range(num_of_elements):
summ += num
num /= -2
print(f'Сумма {num_of_elements} элементов ряда: {summ}')
else:
print('Ошибка! Необходимо ввести положительное целое число больше 0')
except ValueError:
print('Ошибка! Необходимо ввести целое число')
| false |
d90b0446da8f2201d5bc0ac0bed1b15dca86eefd | qikuta/python_programs | /text_to_ascii.py | 760 | 4.5 | 4 | # Quentin Ikuta
# August 7, 2022
# This program takes input from user, anything from a-z, A-Z, or 0-9 --
# converts the input into ASCII code, then finally prints the original input and ASCII code.
# ask user for input
user_string = input("please enter anything a-z, A-Z, and/or 0-9:")
# iterate through each character and/or number, compare to dictionary of ASCII, pull the appropriate ASCII letter.
asciiDict = {i: chr(i) for i in range(128)}
keyList = list(asciiDict.keys())
valList = list(asciiDict.values())
def letter_to_ascii(user_string):
indexlist = []
for letter in user_string:
letterindex = valList.index(letter)
indexlist.append(letterindex)
return indexlist
print(letter_to_ascii(user_string))
print(user_string)
| true |
2b3cb34f4d91c43bd4713619e0adbd53dbd6f17e | ICANDIGITAL/crash_course_python | /chapter_7/restaurant_seating.py | 230 | 4.1875 | 4 | seating = input("How many people are in your dinner group? ")
seating = int(seating)
if seating >= 8:
print("You'll have to wait for a table of " + str(seating) + ".")
else:
print("There is currently a table available.") | true |
d415802c81d337356a85c4c0f94ca993fbcb1d7d | ICANDIGITAL/crash_course_python | /chapter_8/unchanged_magicians.py | 421 | 4.125 | 4 | def show_magicians(magicians):
"""Displays the name of each magicians in a list."""
for magician in magicians:
print(magician.title())
magical = ['aalto simo', 'al baker', 'alessandro cagliostro', 'paul daniels']
def make_great(tricks):
"""Modifies the original function by adding a message."""
for great in range(len(tricks)):
tricks[great] += " the great".title()
make_great(magical[:])
show_magicians(magical)
| true |
d13d378ac3ba53279864e205439454b893c52dbf | monkop/Data-Structure-in-Python | /Sorting/bubble_sort.py | 441 | 4.28125 | 4 | arr = []
n = int(input("Enter size of array :")) #this input ask for our array size
for i in range(n):
n1 = int(input("Enter Array : "))
arr.append(n1)
print("Your Array : ",arr) #for Showing Your actual array
for i in range(n):
for j in range(n-1-i):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
print("Your Sorted Array Is : ",arr) | false |
7cd438649c6339d0c494ceaac380295e75aa2a97 | monkop/Data-Structure-in-Python | /Arrays/insertionSort.py | 382 | 4.125 | 4 | arr = []
n = int(input("Enter Size Of array : "))
for i in range(n):
array = int(input("Enter Lisy Of Array : "))
arr.append(array)
print("Your Unsorted Array",arr)
for i in range(1,n):
temp = arr[i]
j = i-1
while j >= 0 and arr[j] > temp:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = temp
print("Your Sorted Is : ", arr) | false |
5550808695e2649c4c0f1136ba6ddf741ac1da8a | monkop/Data-Structure-in-Python | /Arrays/bu_pratice.py | 401 | 4.125 | 4 | arr = []
n = int(input("Enter size of array : "))
for i in range(n):
array = int(input("Enter list of array : "))
arr.append(array)
print(f"Your Unsorted Array {arr}")
for i in range(0,n):
for j in range(n-1-i):
if(arr[j] > arr[j+1]):
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
print(arr)
print("Your Sorted array is : ", arr) | false |
e75281768755ccae44dc2ea91b4cba0f1b775f3a | monkop/Data-Structure-in-Python | /Arrays/PraticeBS.py | 348 | 4.125 | 4 | arr = []
n = int(input("Size : "))
for i in range(n):
array = int(input("Enter List Of array : "))
arr.append(array)
print(f"Your Array {arr}")
for i in range(n-1):
for j in range(n-1-i):
if(arr[j] > arr[j+1]):
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
print("Sorted Array is :",arr)
| false |
be760a2488631c90a135637a524a857ee1bfc7d3 | Divyansh-coder/python_challenge_1 | /area_of_circle.py | 244 | 4.5625 | 5 | #import math to use pi value
import math
#take radius as (real number)input from user
radius = float(input("Enter the radius of the circle: "))
#print area of circle
print("The area of the circle with radius",radius,"is :",math.pi*radius**2)
| true |
7a287ab16b4fa019dc5190951f5f6268ae9d6d0b | Mannuel25/Mini-Store-Project | /items_in_file.py | 657 | 4.34375 | 4 | def no_of_items_in_file():
"""
Displays the total number of
items in the file
:return: None
"""
filename = 'myStore.txt'
# open original file to read its contents
open_file = open(filename,'r')
description = open_file.readline()
# make a variable to count the number of items
TOTAL = 0
while description != '':
TOTAL += 1
description = open_file.readline()
open_file.close()
# since each record consists of three fields
# divide the total number of items by 3
# in the file and round it to the nearest whole number
print(f'Total number of items in file: {round(TOTAL / 3)}') | true |
2e93d1859265eb0f7f53a7a34c2458c8201acc20 | xiaofeixiawang/cs101 | /lesson5/problem-set2.py | 1,744 | 4.1875 | 4 | 1.
# Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
if letter=='z':
return 'a'
return chr(ord(letter)+1)
print shift('a')
#>>> b
print shift('n')
#>>> o
print shift('z')
#>>> a
2.
# Write a procedure, shift_n_letters which takes as its input a lowercase
# letter, a-z, and an integer n, and returns the letter n steps in the
# alphabet after it. Note that 'a' follows 'z', and that n can be positive,
#negative or zero.
def shift_n_letters(letter, n):
return chr((ord(letter)-ord('a')+n)%26+ord('a'))
print shift_n_letters('s', 1)
#>>> t
print shift_n_letters('s', 2)
#>>> u
print shift_n_letters('s', 10)
#>>> c
print shift_n_letters('s', -10)
#>>> i
3.
# Write a procedure, rotate which takes as its input a string of lower case
# letters, a-z, and spaces, and an integer n, and returns the string constructed
# by shifting each of the letters n steps, and leaving the spaces unchanged.
# Note that 'a' follows 'z'. You can use an additional procedure if you
# choose to as long as rotate returns the correct string.
# Note that n can be positive, negative or zero.
def shift_n_letters(letter, n):
return chr((ord(letter)-ord('a')+n)%26+ord('a'))
def rotate(word,n):
res=''
for letter in word:
if letter==' ':
res+=' '
else:
res+=shift_n_letters(letter,n)
return res
print rotate ('sarah', 13)
#>>> 'fnenu'
print rotate('fnenu',13)
#>>> 'sarah'
print rotate('dave',5)
#>>>'ifaj'
print rotate('ifaj',-5)
#>>>'dave'
print rotate(("zw pfli tfuv nfibj tfiivtkcp pfl jyflcu "
"sv rscv kf ivru kyzj"),-17)
#>>> ??? | true |
e424eb0df975b287825768065921bdac8473c72d | RaisuFire/ExProject | /leetCode/Medium/Rotate Image.py | 758 | 4.125 | 4 | from copy import deepcopy
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
c = deepcopy(matrix)
for i in range(len(matrix)):
matrix[i] = [c[j][i] for j in range(len(c[i]))][::-1]
"""
matrix.reverse()
r = len(matrix)
for i in range(r):
for j in range(i+1, r):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
return
"""
if __name__ == "__main__":
nums1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
so = Solution()
c = so.rotate(nums1)
print(c)
| true |
aeca2a9b20564854381cba2a7478f5cfbb266201 | sumitdba10/learnpython3thehardway | /ex11.py | 1,108 | 4.25 | 4 | print("How old are you?", end=' ')
age = input()
print("How tall are you in inches?",end=' ')
height = input()
print("How much do you weigh in lbs?",end=' ')
weight = input()
# end=' ' at the end of each print line. This tells print to not end the line with a newline character and go to the next line.
print(f"So, you're {age} old, {height} inches tall, and {weight} pounds heavy.")
print("#"*50)
################################################################################
#ex12.py
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much you weigh? ")
print(f"So, you're {age} old, {height} inches tall, and {weight} pounds heavy.")
print("#"*50)
###############################################################################
#ex13.py
# importing a feature from Python feature statement
#argv is argument variable, it holds arguments as value
from sys import argv
script, first, second, third = argv
print("The script is called:",script)
print("The first variable is:",first)
print("The second variable is:",third)
print("The third variable is:",third)
| true |
f1169d8cfd40df1dcf07287ffaab636bb51f28db | sumitdba10/learnpython3thehardway | /ex20.py | 1,856 | 4.5625 | 5 | # from sys package, we are importing argument variables module
from sys import argv
import os
# asigning two variables to argv module
script,input_file = argv
# defining a function to read all content of a file
def print_all(f):
print(f.read())
# defining a function to reset pointer to 0 position
def rewind(f):
f.seek(0)
# defining a function to read one line from file
def print_a_line(line_count, f):
print(line_count,f.readline())
# defining a function to append the existing file with new entries, and save it using close() method of file class
def write_to_file(f):
f.write(input())
f.write("\n")
f.close()
# opening file and saving contents to variable
current_file = open(input_file)
print(f"First let's print the content of whole file {input_file}: ")
print("\n")
# while using f formatting method, how can we use \n formatter in string
# calling print_all function to print all the content of file
print_all(current_file)
print("Now, Let's rewind, kind of like a tape \n")
rewind(current_file)
print("Let's print three lines.\n")
current_line =1
print_a_line(current_line,current_file)
current_line += 1
print_a_line(current_line,current_file)
current_line+=1
print_a_line(current_line,current_file)
# opening file in append mode
current_file = open(input_file,"a")
print(f"Add a new line to {input_file} file.")
# now as file is append mode, we can write new contents to it
write_to_file(current_file)
print("\n")
# As file was in write mode, we would not be able to read it directly, So opening same file in read mode
current_file = open(input_file,"r")
# printing all contents
print_all(current_file)
#######################################################################
# Questions for future:
# How can I delete specific line from a input_fileself.
# How can I edit the content of exisiting file.
| true |
6ff3500c81ed429be175c5610a853c2e0f98a728 | sumitdba10/learnpython3thehardway | /ex23.py | 1,738 | 4.5625 | 5 | # importing sys package
import sys
#assigning three variables to argv (argument variable) module
# script : this whole program as .py
# encoding : variable to define encoding e.g. unicode - utf8/utf16/utf32 or ASCII etcself.
#error : to store errors
script,encoding, errors = sys.argv
# defining a function with 3 arguments , the input file, encoding and errors
def main(language_file,encoding, errors):
# reading lines from file and assigning to a Variable
line = language_file.readline()
# if condition, if we have a line in file then
if line:
#execute the print_line function which is defined below
print_line(line,encoding,errors)
# also, return main function again to continue with readline
return main(language_file,encoding,errors)
def print_line(line,encoding,errors):
# we are using line variable from main function above, using .strip() function of a string we strip both trailing and leading whiespaces are removed from string
next_lang = line.strip()
# raw bytes is a sequence of bytes that python uses to store utf-8 encoded string
# next_lang is a variable which has stripped line from language input input_file
# we are encoding each line in raw bytes using encode method
raw_bytes = next_lang.encode(encoding,errors=errors)
# we are decoding raw bytes to utf-8 string using decode method
cooked_string = raw_bytes.decode(encoding,errors=errors)
# Now printing bytes encoding and utf-8 character equivalent to each other
print(raw_bytes, '<====>',cooked_string)
# opening input file in utf-8 unicode encoding
languages = open("languages.txt",encoding ="utf-8")
# Now finally calling main function
main(languages,encoding,errors)
| true |
c640eccb766d3be16d513516ca9b3bb7499df39e | Sophorth/mypython_exercise | /ex11.py | 569 | 4.4375 | 4 | print " "
print " ------Start Exercise 11, Asking Question ------"
print " "
print "What is your name: ",
name = raw_input()
print "How tall are you: ",
height = raw_input()
print "How old are you: ",
age = raw_input()
print "You name is %s and your are %s inches tall and you are %s" % (name, height, age)
# We can do it in another way as bellow:
name = raw_input("What is your name? :")
height = raw_input("How tall are you? :")
age = raw_input("How old are you? :")
print "Again, Your name is %s and your are %s inches tall and you are %s" % (name, height, age)
| true |
9fb33802cd8348fc3fa37be0c0bc61e81bfb683c | nojronatron/PythonPlayarea | /PycharmProjects/Chapter4Explorations/Heros_Inventory.py | 1,366 | 4.25 | 4 | __author__ = 'Blue'
# Hero's Inventory
# Demonstrates tuple creation
# Create an empty Tuple
inventory = ()
# Treat the tuple as a condition
if not inventory:
print("You are empty-handed.")
# create a tuple with some items
inventory = ("sword",
"armor",
"shield",
"healing potion")
# print the tuple
print("\nYou have:", (len(inventory)), "items in your inventory.")
# print each element in the tuple
print("\nYour items:")
for item in inventory:
print(item)
# Test for membership with 'in'
if "healing potion" in inventory:
print("\nYou will live to fight another day.")
# Display one item through an index
index = int(input("\nEnter the index number for an item in inventory: "))
if index < 1:
index = 1
print("\nThat number is too low, so I'll assume you meant the first item in inventory.")
if index > len(inventory):
index = len(inventory)
print("\nThat number is too high, so I'll assume you meant the last item in inventory.")
print("At index", index, "is", inventory[index - 1])
# Concatenate two tuples (since they are immutable)
chest = ("gold", "gems")
print("\nYou find a chest. It contains:")
print(chest)
print("You add the contents of the chest to your inventory.")
inventory += chest
print("Your inventory is now:")
print(inventory)
input("\nPress the Enter key to exit.")
| true |
aca33cc8e9e6394ba986c45caf8d3eb96f8e367c | nojronatron/PythonPlayarea | /PycharmProjects/Chapter 4 Exercizes/Word_Jumble_Game.py | 1,319 | 4.25 | 4 | # -------------------------------------------------#
# Title: Chapter 4: Word Jumble Game
# Author: Jon Rumsey
# Date: 3-May-2015
# Desc: Computer picks a random word from a list and jumbles it
# User is asked to guess the word.
# 1. Create sequence of words
# 2. Pick one word randomly from the sequence
# 3. Create a new word sequence and re-arrange the letters to form the jumble
# 4. Loop the player through guesses
# 5. Congratulate player, ask if done/play again
# ChangeLog: Initial
#-------------------------------------------------#
#-- Data --#
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
jumble = ""
#-- Processing --#
word = random.choice(WORDS)
correct = word
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
#-- Presentation (I/O) --#
print("\tWelcome to Word Jumble!")
print("\nUnscramble the letters to make a word.")
print("\n\nThe jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
guess = input("Your guess: ")
if guess == correct:
print("\nThat's it! You guessed it!\n")
print("Thanks for playing.")
input("\n\nPress the Enter key to exit.") | true |
56321bc2ea255b211551506b56bc2e255cdcd34d | rahuldevyadav/Portfolio-PYTHON | /gui/program2.py | 436 | 4.375 | 4 | #In this program we will create frame
#size of widget
#and putting button on it
from tkinter import *
root= Tk()
frame = Frame(root, width=300,height =200)
# ONCE WE DEFINE BUTTON WIDTH AND HEIGHT IS DEFAULT
button = Button(frame,text='Button1')
button.pack()
frame.pack()
#
# frame2 = Frame(root,width=300,height =200)
# button2 = Button(frame2,text="default")
# button2.pack(side=LEFT)
# frame2.pack(side=BOTTOM)
root.mainloop()
| true |
4c4eda77068ff3b077039b6cdad46f29b679cb94 | Erivks/aprendendo-python | /POO/POOIII/Objetos e Dicionários.py | 1,430 | 4.375 | 4 | #COMPARAÇÃO ENTRE OBJETOS E DICIONÁRIOS E
# MÉTODO ESPECIAL PARA DICIONÁRIOS
'''DICIONÁRIO'''
#Criando dict
pessoa = {'Nome': 'Lucas', 'Emprego': 'Advogado', 'Idade': 20, 'Cor de cabelo': 'Pedro'}
#Mudando um valor dentro do dict
pessoa['Nome'] = 'Erick'
#Acessando valor
print(pessoa['Emprego'])
#Criando novas chaves
pessoa['Peso'] = 87.0
#Olhando um dict e comparando com uma class,
# não são muito diferentes e para comparação faremos uma classe Pessoa
class Pessoa(object):
pass #criando uma classe vazia com statement pass
#Criando objeto
Lucas = Pessoa()
#Criando atributos para o objeto
Lucas.nome = 'Lucas'
Lucas.idade = 27
Lucas.emprego = 'Advogado'
'''Em python, os objetos criados são
adicionados internamente dentro de um dicionario'''
dicionario = Lucas.__dict__ #Método especial que retorna o objeto como um dicionário
print(dicionario)
'''Objetos são mais vantajosos:
Pela facilidade de se trabalhar com eles;
Por ser mais fácil criar vários objetos, cada um com seus métodos;
Em objetos, existem as Heranças, Polimofismo e Encapsulamento.
Em objetos, sabemos exatamente os paramêtros que devem ser passados'''
#Um dos motivos pelo qual Python é uma linguagem mais lenta,
# é pelo fato de que os objetos são armazenados em dict's
#Assim como pode-se usar o método __dict__ em objetos,
# também é possível usá-lo em classes para saber seus métodos
print(Pessoa.__dict__) | false |
8a80887a2d41386d9f9097abc97c08298076757d | learnPythonGit/pythonGitRepo | /Assignments/20200413_Control_Flow/secondLargeNumSaurav.py | 998 | 4.40625 | 4 | # ....................................
# Python Assignment :
# Date : 15/04/2020 :
# Developer : Saurav Kumar :
# Topic : Find Second Largest Num :
# Git Branch: D15042020saurav :
# ...................................
# Compare two number and find out the greater number (using if else)
print("Assignment : Find second largest of the given numbers in list - Method 1")
lst = [3, 2, 7, 4, 6, 6, 5, 8]
# sorting of list
newList = []
for i in lst:
if i not in newList:
newList.append(i)
newList.sort(reverse=True)
print("Second Largest number is {0}".format(newList[1]))
# FInd the second Largest number from the list of Number- Ashish
print("Assignment : Find second largest of the given numbers in list - Method 2")
number_list = [1,2,3,4,2,1,5,6,8,4,1,5,1,5,4,8]
number_list = list(set(number_list))
number_list.sort(reverse=True)
print("Second Largest number is {0}".format(number_list[1]))
print("\n" + "-"*80)
| true |
cd1f6862b5cae32aa0b6b28c6c084ef3d69afa5c | learnPythonGit/pythonGitRepo | /Assignments/20200413_Control_Flow/ControlFlowAssignments_Kiran.py | 2,828 | 4.40625 | 4 | # :................................................................................:
# : Python Assignment. :
# :................................................................................:
# : Date : 15/04/2020 :
# : Developer : Kiran Lohar :
# : Topic : Python Loops: Control flow. :
# : Git Branch : Assignments/ControlFlow :
# :................................................................................:
#1. Compare two number and find out the greater number (using if else)
print("Find out the greater number....")
print("Enter two numbers: ")
number_one = int(input())
number_two = int(input())
if number_one > number_two:
print(str(number_one) + ' is greater than ' + str(number_two))
elif number_two > number_one:
print(str(number_two) + ' is greater than ' + str(number_one))
else:
print('Both numbers are EQUAL')
#2. Write a program to check if the given number is +ve or -Ve or its 0. (using if else)
print('-----------------------------------------------------------------')
print("Check the number is positive or negative....")
print('Please enter a number of your choice: ')
number = int(input())
if number < 0:
print(str(number) + ' is negative number')
elif number > 0:
print(str(number) + ' is positive number')
else:
print('The number entered is ZERO')
#3. Check if the given string is a palindrome sting/word.(using if...else and for/while loop)
print('-----------------------------------------------------------------')
print("Test if the sting is palindrome string....")
print('Enter string/word: ')
input_string = str(input())
upper_string = input_string.upper()
i = 0
j = len(input_string)-1
k = '0'
while i != j:
if upper_string[i] != upper_string[j]:
k = '1'
i += 1
j -= 1
if i > j:
break
if k != '1':
print('The string \"' + input_string + '\" is palindrome')
else:
print('The string \"' + input_string + '\" is not palindrome')
#4. Count the number of vowels and consonants in the string/word. (using if...else, for/while loop)
print('-----------------------------------------------------------------')
print('Count the number of vowels and consonants....')
input_string = 'My daughters name is Ojaswi'
print('String is: ' + input_string)
vowels = ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']
vowels_count = 0
consonants_count = 0
for i in input_string:
if i in vowels:
vowels_count += 1
elif i != ' ':
consonants_count += 1
print("Vowels count = " + str(vowels_count))
print("Consonants count = " + str(consonants_count))
| false |
636a447d89387773056d4e81c6a7519cea3675dd | TCIrose/watchlist | /app/models/movie.py | 1,124 | 4.125 | 4 | class Movie:
'''
Movie class to define Movie Objects
'''
def __init__(self, id, title, overview, poster, vote_average, vote_count):
'''
Args:
1. Title - The name of the movie
2. Overview - A short description on the movie
3. image- The poster image for the movie
4. vote_average - Average rating of the movie
5. vote_count - How many people have rated the movie
6. id - The movie id
'''
self.id = id
self.title = title
self.overview = overview
self.poster = 'https://image.tmdb.org/t/p/w500/'+ poster
self.vote_average = vote_average
self.vote_count = vote_count
'''
def __repr__(self):#, id, title, overview, poster, vote_average, vote_count):
self.id = "%s" % (self.id)
self.title = "%s" % (self.title)
self.overview = "%s" % (self.overview)
self.poster = "%s" % (self.poster)
self.vote_average = "%s" % (self.vote_average)
self.vote_count = "%s" % (self.vote_count)
'''
| true |
4b11b5f80610aa514338426c0b0262b20c81aa3c | Cretis/Triangle567 | /TestTriangle.py | 2,667 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Updated Jan 21, 2018
The primary goal of this file is to demonstrate a simple unittest implementation
@author: jrr
@author: rk
"""
import unittest
from Triangle import classifyTriangle
# This code implements the unit test functionality
# https://docs.python.org/3/library/unittest.html has a nice description of the framework
class TestTriangles(unittest.TestCase):
# define multiple sets of tests as functions with names that begin
def testRightTriangleA(self):
self.assertEqual(classifyTriangle(3, 4, 5), 'Right', '3,4,5 is a Right triangle')
def testRightTriangleB(self):
self.assertEqual(classifyTriangle(5, 3, 4), 'Right', '5,3,4 is a Right triangle')
def testRightTriangleC(self):
self.assertEqual(classifyTriangle(3, 5, 4), 'Right', '3,5,4 is a Right triangle')
def testEquilateralTrianglesA(self):
self.assertEqual(classifyTriangle(1, 1, 1), 'Equilateral', '1,1,1 should be equilateral')
def testEquilateralTrianglesB(self):
self.assertEqual(classifyTriangle(200, 200, 200), 'Equilateral', '200,200,200 should be equilateral')
def testNotATriangleA(self):
self.assertEqual(classifyTriangle(1, 2, 10), 'NotATriangle', '1,2,10 is not a Triangle')
def testNotATriangleB(self):
self.assertEqual(classifyTriangle(10, 1, 2), 'NotATriangle', '10,1,2 is not a Triangle')
def testNotATriangleC(self):
self.assertEqual(classifyTriangle(2, 10, 1), 'NotATriangle', '2,10,1 is not a Triangle')
def testNotATriangleD(self):
self.assertEqual(classifyTriangle(1, 2, 3), 'NotATriangle', '1,2,3 is not a Triangle')
def testInvalidIputA(self):
self.assertEqual(classifyTriangle(201, 201, 201), 'InvalidInput', '201,201,201 is invalid input')
def testInvalidIputB(self):
self.assertEqual(classifyTriangle(0, 1, 2), 'InvalidInput', '0,1,2 is invalid input')
def testInvalidIputC(self):
self.assertEqual(classifyTriangle(1, 5, 300), 'InvalidInput', '1,5,300 is invalid input')
def testInvalidIputD(self):
self.assertEqual(classifyTriangle(0, 0, 0), 'InvalidInput', '0,0,0 is invalid input')
def testInvalidIputE(self):
self.assertEqual(classifyTriangle(0.1, 0.1, 0.1), 'InvalidInput', '0.1,0.1,0.1 is invalid input')
def testIsocelesTriangle(self):
self.assertEqual(classifyTriangle(2, 2, 3), 'Isoceles', '2,2,3 is a Isoceles Triangle')
def testScaleneTriangle(self):
self.assertEqual(classifyTriangle(5, 6, 7), 'Scalene', '5,6,7 is a Scalene Triangle')
if __name__ == '__main__':
print('Running unit tests')
unittest.main()
| true |
9971c2273e83ae2010a55f76d3f3c8871098bb53 | technolawgeek/HW | /Lesson1/Task5.py | 2,048 | 4.1875 | 4 | """
Запросите у пользователя значения выручки и издержек фирмы.
Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек,
или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью,
вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите численность
сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
"""
while True:
income = input("Введите размер вашей выручки:\n")
if income.isdigit():
income = int(income)
break
else:
print("Введите цифры, вы ввели что-то другое")
while True:
outcome = input("Введите размер ваших исдержкек:\n")
if outcome.isdigit():
outcome = int(outcome)
break
else:
print("Введите цифры, вы ввели что-то другое")
if income >= outcome:
print("Ваш бизнес приносит прибыль")
num_of_workers = input("Сколько у вас сотрдников:\n")
while True:
if num_of_workers.isdigit():
num_of_workers = int(num_of_workers)
break
else:
print("Введите цифры, вы ввели что-то другое")
print("Рентабельность вашей выручки составляет: ", (income - outcome) / income * 100)
print("Прибыль на каждого сотрудника составит (пр/1 чел):", (income - outcome) / num_of_workers)
else:
print("Вы работаете с убытком")
| false |
7cbea7f0bd0645048484806489ed71c2c6e580b7 | wonpyo/Python | /Basic/VariableScope.py | 1,207 | 4.3125 | 4 | # Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used.
# Python supports global variables (usable in the entire program) and local variables.
# By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’.
print("[Local Variable]\n")
def sum(x,y):
sum = x + y
return sum
print(sum(8,6))
# print(x) # Local variables cannot be used outside of their scope, this line will not work
print()
def f(x,y):
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))
z = 4 # local variable
print('Local variable z = ' + str(z))
z = 3 # global variable
f(3,2)
print('Global variable z = ' + str(z))
print()
print("[Global Variable]\n")
z = 10
def afunction():
global z
z = 9
afunction()
print("z = " + str(z))
print('')
z = 10
print("z = " + str(z))
def func1():
global z
z = 3
def func2(x,y):
global z
return x+y+z
func1()
print("z = " + str(z))
total = func2(4,5)
print("total = ", total)
| true |
25209b004ddb4eae65d34e63235622fa9fa44a3d | wonpyo/Python | /Basic/MethodOverloading.py | 1,019 | 4.4375 | 4 | # Several ways to call a method (method overloading)
# In Python you can define a method in such a way that there are multiple ways to call it.
# Given a single method or function, we can specify the number of parameters ourself.
# Depending on the function definition, it can be called with zero, one, two or more parameters.
# This is known as method overloading.
# Not all programming languages support method overloading, but Python does.
# We create a class with one method sayHello(). The first parameter of this method is set to None,
# this gives us the option to call it with or without a parameter.
# An object is created based on the class, and we call its method using zero and one parameter.
class Human:
def sayHello(self, name=None):
if name is not None:
print('Hello ' + name)
else:
print('Hello ')
# Create an instance (object)
obj = Human()
# Call the method without parameter
obj.sayHello()
# Call the method with a parameter
obj.sayHello("Wonpyo") | true |
a2cfdf0723538af644a2eee5372069785bdc048e | wonpyo/Python | /Basic/Threading.py | 1,526 | 4.53125 | 5 | """
A thread is an operating system process with different features than a normal process:
1. Threads exist as a subset of a process
2. Threads share memory and resources
3. Processes have a different address space in memory
When would you use threading?
Usually when you want a function to occur at the same time as your program.
If you want the server not only listens to one connection but to many connections.
In short, threads enable programs to execute multiple tasks at once.
"""
from threading import *
import time
print("Example #1: Create and start 10 threads")
class MyThread(threading.Thread):
def __init__(self, x): # constructor
self.__x = x
threading.Thread.__init__(self)
def run(self):
print(str(self.__x))
# Start 10 threads: Threads do not have to stop if run once
for x in range(10):
MyThread(x).start()
print()
print("Example #2: Timed threads")
def hello():
print("Hello Python!")
# Create timed thread by instantiating Timer class
t = Timer(10.0, hello())
# Start the thread after 10 seconds
t.start()
print()
print("Example #3: Repeat functionality using threads")
def handleClient1():
while(True):
print("Waiting for client 1...")
time.sleep(5) # Wait for 5 seconds
def handleClient2():
while(True):
print("Waiting for client 2...")
time.sleep(5) # Wait for 5 seconds
# Create timed threads
t1 = Timer(5.0, handleClient1())
t2 = Timer(3.0, handleClient2())
# Start threads
t1.start()
t2.start()
| true |
50a126e7540a343ff18cbe16262324bf091cc0a4 | cameron-teed/ICS3U-3-08-PY | /leap-year.py | 548 | 4.34375 | 4 | #!/usr/bin/env python3
# Created by: Cameron Teed
# Created on: Oct 2019
# This is program finds out if it's a leap year
def main():
# calculates if it is a leap year
# variables
leap_year = " is not"
# input
year = int(input("What is the year: "))
# process
# output
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
leap_year = " is"
else:
leap_year = " is"
print(str(year) + leap_year + " a leap year.")
if __name__ == "__main__":
main()
| true |
50cdfe6dd5d6826a19477bbd440f7b1af507619e | ElleDennis/build-a-blog | /crypto/helpers.py | 1,276 | 4.4375 | 4 | def alphabet_position(letter):
"""alphabet_position receives single letter string & returns 0-based
numerical position in alphabet of that letter."""
alphabetL = "abcdefghijklmnopqrstuvwxyz"
alphabetU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
letter = letter.lower()
if letter in alphabetL:
return alphabetL.find(letter)
if letter in alphabetU:
return alphabetU.find(letter)
def rotate_character(char, rot):
"""rotate_character receives single string character & an integer
for rotation (rot) to places right in alphabet."""
alphabetL = "abcdefghijklmnopqrstuvwxyz"
alphabetU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if char.isalpha() == False:
#to ignore all non-alpha chars
return char
if char.isupper():
rotated_let_num = alphabet_position(char)
"""Calling the above function"""
rotated_let_num = (rotated_let_num + int(rot)) % 26
encrypted_letter_upper = alphabetU[rotated_let_num]
return encrypted_letter_upper
else:
rotated_let_num = alphabet_position(char)
"""Calling the above function"""
rotated_let_num = (rotated_let_num + int(rot)) % 26
encrypted_letter = alphabetL[rotated_let_num]
return encrypted_letter
| true |
4ad19fd2cc5629774a834fbffcdfae0e56c40a05 | tanyuejiao/python_2.7_stuty | /lxf/interation2.py | 1,182 | 4.25 | 4 | #!/usr/bin/python
# coding:utf-8
# 当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。
# 那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:
from collections import Iterable
# 可以使用isinstance()判断一个对象是否是Iterable对象:
# str是否可迭代
a = isinstance("abc", Iterable)
print ("a: %s" % a)
# list是否可迭代
a = isinstance([1, 2, 3], Iterable)
print ("a: %s" % a)
# 整数是否可迭代
a = isinstance(123, Iterable)
print ("a: %s" % a)
a = isinstance((x for x in range(10)), Iterable)
print ("a: %s" % a)
# 如果要对list实现类似Java那样的下标循环怎么办?
# Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
# 0 A
# 1 B
# 2 C
# 上面的for循环里,同时引用了两个变量,在Python里是很常见的,比如下面的代码:
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y) | false |
ef79d66df178986222288328d66bb6daa3a4b3f1 | tanyuejiao/python_2.7_stuty | /lxf/class2.py | 1,908 | 4.125 | 4 | #!/usr/bin/python
# coding:utf-8
import types
'''获取对象信息
当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
使用type()
首先,我们来判断对象类型,使用type()函数:
基本类型都可以用type()判断:'''
print type(123)
# <class 'int'>
print type('str')
# <class 'str'>
print type(None)
# <type(None) 'NoneType'>
# 如果一个变量指向函数或者类,也可以用type()判断:
def abs():
pass
class Animal(object):
def __init__(self):
print "animal"
a = Animal()
print type(abs)
# <class 'builtin_function_or_method'>
print type(a)
# <class '__main__.Animal'>
# 比较两个变量的type类型是否相同:
print type(123) == type(456)
# True
print type(123) == int
# True
print type('abc') == type('123')
# True
print type('abc') == str
# True
print type('abc') == type(123)
# False
# 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:
def fn():
pass
print type(fn) == types.FunctionType
# True
print type(abs) == types.BuiltinFunctionType
# True
print type(lambda x: x) == types.LambdaType
# True
print type((x for x in range(10))) == types.GeneratorType
# True
# 能用type()判断的基本类型也可以用isinstance()判断:
print isinstance('a', str)
# True
print isinstance(123, int)
# True
print isinstance(b'a', bytes)
# True
# 可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:
print isinstance([1, 2, 3], (list, tuple))
# True
print isinstance((1, 2, 3), (list, tuple))
# True
# 使用dir()
# 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:
print dir('ABC') | false |
e1a296cfe2eb437daad088ff4070a689872bb03e | ishaik0714/MyPythonCode | /Strings_Prog.py | 1,232 | 4.375 | 4 | mult_str = """This is a multi line string,
this can have data in multiple lines
and can be printed in multiple lines !"""
print(mult_str) # The Multi-line string can be in either in three single quotes or three double quotes.
st1 = "Hello"
st2 = "World!"
print (st1+st2) # String Concatenation
str1 = "Hello World!" # Character position in a String start from 0
print("Character at position - 0 of the string: ",str1[0]) # First Character is 0
print("Sub-string from position 3 to 5: ", str1[2:5]) # 2:5 means characters at position 3rd, 4th and 5th
print("Sub-string from position -6 to -3 from end: ",str1[-6:-3]) # Negative number means, start counting from the end of string starting with 0
print("String length: ",len(str1)) # Get the string length
print("String remove whitespace: ",str1.strip()) # Remove white spaces in string
print("String to lower case: ",str1.lower()) # change the string to lower case
print("String to upper case: ",str1.upper()) # change the string to upper case
print("String to upper case: ",str1.replace('H','M')) # Replace H with M
print("String to upper case: ",str1.split(',')) # change the string to upper case
987654321
HELLOWORD
012345678
[3:6] =
[-4:-1] = | true |
8698aa545749d13a550704ba005888e0fbb0001f | syedsouban/PyEditor | /PyEditor.py | 1,690 | 4.15625 | 4 | import sys
print("Welcome to Python 2 Text Editor")
condition = True
while condition == True:
print("""What do you want to do:
1. Creating a new file
2. Writing to a saved file
3. Viewing a saved file
4. Exit """)
choice=eval(input("Enter your choice: "))
if choice==4:
sys.exit()
elif choice==3:
mode="r"
file_name=input("Enter your filename: ")
File=open(file_name,mode)
print(File.read())
elif choice==2:
mode="a+"
file_name=input("Enter your filename: ")
File=open(file_name,mode)
print(File.read())
File.close()
File=open(file_name,mode)
while True:
new_text=input()
File.write((new_text)+'\n')
elif choice==1:
mode="w+"
file_name=input("Enter your filename: ")
File=open(file_name,mode)
File.truncate()
print("Start writing your text from here(Press Ctrl+Z and then Press Enter for stop writing): ")
while True:
new_text=input()
File.write((new_text)+'\n')
else:
print("Invalid choice entered")
char=input("Press C/c to continue and Q/q to quit: ")
if char=='C' or char == 'c':
condition=True
elif char=='q' or char=='Q':
condition=False
else:
print("Invalid choice entered")
File.close()
#addong a commit, bruuuh.
| true |
d44ab2f4b12fbeb112faceddf889d477f0c796b2 | sunil830/PracticePerfect | /ListOverlap.py | 1,315 | 4.25 | 4 | """
Author: Sunil Krishnan
Date: 17-Apr-2016
Name: ListOverlap.py
Reference: http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
Problem Statement:
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements
that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
Extras:
Randomly generate two lists to test this
Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
"""
import random
def findlistoverlap(a, b):
print([x for elem in a for x in b if elem == x])
def randomlist():
v_num = int(input('Enter the number of elements you want in the generated list: '))
a = random.sample(range(100), v_num)
b = random.sample(range(100), v_num)
findlistoverlap(a, b)
def staticlist():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
findlistoverlap(a, b)
if __name__ == '__main__':
v_yes_no = str(input('Enter Y for Random List and N for Static List: '))
if v_yes_no == 'Y':
randomlist()
else:
staticlist()
| true |
447a4be3d6ce706a5bce989a1874910855360883 | bthodla/stock_tweets | /turtle_utils.py | 966 | 4.1875 | 4 | import turtle
import math
import time
def polyline(t: turtle, sides: int, length: int, angle: int):
"""Draws *sides* line segments with the given length and angle (in degrees) between them
:param t: turtle
:param sides:
:param length:
:param angle:
:return:
"""
for i in range(sides):
t.fd(length)
t.lt(angle)
def polygon(t: turtle, sides: int, length: int):
angle = 360 / sides
polyline(t, sides, length, angle)
time.sleep(1)
def square(t: turtle, length: int):
polygon(t, 4, length)
def triangle(t: turtle, length: int):
polygon(t, 3, length)
def arc(t: turtle, radius: int, angle: int):
arc_length = 2 * math.pi * radius * angle / 360
sides = int (arc_length / 3) + 1
step_length = arc_length / sides
step_angle = float (angle) / sides
polyline(t, sides, step_length, step_angle)
def circle(t: turtle, radius: int):
angle = 360
arc(t, radius, angle)
| false |
b2c0f4d56af52930fb94356d565dc2a7822acd3b | KennethTBarrett/cs-module-project-iterative-sorting | /src/iterative_sorting/iterative_sorting.py | 2,050 | 4.40625 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# For loop, in range of untouched indexes.
for index in range(i + 1, len(arr)):
# Check if the current smallest is still the smallest.
if arr[smallest_index] > arr[index]: # If so...
smallest_index = index # Update the smallest index.
#Swap the values around.
arr[i], arr[smallest_index] = arr[smallest_index], arr[i]
return arr
# Quadratic runtime. - O(n^2)
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# We're going to need to iterate over the entire array.
for i in range(len(arr)):
for index in range(0, len(arr)-i-1): # Last elements already in place
# If the current index is greater than the next...
if arr[index] > arr[index + 1]:
# Swap the values around.
arr[index], arr[index+1] = arr[index+1], arr[index]
return arr
# Quadratic runtime. - O(n^2)
'''
STRETCH: implement the Counting Sort function below
Counting sort is a sorting algorithm that works on a set of data where
we specifically know the maximum value that can exist in that set of
data. The idea behind this algorithm then is that we can create "buckets"
from 0 up to the max value. This is most easily done by initializing an
array of 0s whose length is the max value + 1 (why do we need this "+ 1"?).
Each buckets[i] then is responsible for keeping track of how many times
we've seen `i` in the input set of data as we iterate through it.
Once we know exactly how many times each piece of data in the input set
showed up, we can construct a sorted set of the input data from the
buckets.
What is the time and space complexity of the counting sort algorithm?
'''
def counting_sort(arr, maximum=None):
# Your code here
return arr
| true |
e8ca51cc2ec589c50b304d5e8b25d04fc9670cc8 | Cbkhare/Challenges | /Fb_beautiful_strings.py | 2,140 | 4.15625 | 4 | #In case data is passed as a parameter
from sys import argv
import string
from operator import itemgetter
file_name = argv[1]
fp = open(file_name,'r+')
contents = [line.strip('\n') for line in fp]
#print (contents)
alphas = list(string.ascii_lowercase) #Else use this list(map(chr, range(97, 123)))
#print (alphas)
for item in contents:
zapak = [ ltr.lower() for ltr in list(item) if ltr.lower() in alphas]
zapak_dict = {}
for zap in zapak:
if zap not in zapak_dict:
zapak_dict[zap]=zapak.count(zap)
summ = 0
count = 26
l = len(zapak_dict)
for z in range(l):
k,v = (max(zapak_dict.items(), key=itemgetter(1))[0],max(zapak_dict.items(), key=itemgetter(1))[1])
summ += count* v
del zapak_dict[k]
count -=1
print (summ)
'''
Credits: This problem appeared in the Facebook Hacker Cup 2013 Hackathon.
When John was a little kid he didn't have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could... he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.
Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it. The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase, so that doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)
You're a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file has a sentence. E.g.
ABbCcc
Good luck in the Facebook Hacker Cup this year!
Ignore punctuation, please :)
Sometimes test cases are hard to make up.
So I just go consult Professor Dalves
Output sample:
Print out the maximum beauty for the string. E.g.
152
754
491
729
646
'''
| true |
fd331cd98a5383c06c45605f4a736462cfd78502 | Cbkhare/Challenges | /remove_char_crct.py | 1,073 | 4.21875 | 4 |
#In case data is passed as a parameter
from sys import argv, getsizeof
#from operator import itemgetter
#import re
#import math
#from itertools import permutations
#from string import ascii_uppercase
file_name = argv[1]
fp = open(file_name,'r+')
contents = [line.strip('\n').split(', ') for line in fp]
for item in contents:
p1 = list(item[0])
p2 = list(item[1])
for w in p2:
if w in p1:
while w in p1:
p1.remove(w)
else:
continue
print (''.join(p1))
'''
Write a program which removes specific characters from a string.
Input sample:
The first argument is a path to a file. The file contains the source strings and the characters that need to be scrubbed. Each source string and characters you need to scrub are delimited by comma.
For example:
how are you, abc
hello world, def
malbororo roro, or
Output sample:
Print to stdout the scrubbed strings, one per line. Ensure that there are no trailing empty spaces on each line you print.
For example:
how re you
hllo worl
malb
'''
| true |
8a4d50a0c008157298bfbd1c818f8192a48b9d5f | Cbkhare/Challenges | /swap_case.py | 878 | 4.15625 | 4 |
#In case data is passed as a parameter
from sys import argv, getsizeof
#from operator import itemgetter
#import re
#import math
#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]
for item in contents:
stack = []
for it in item:
if it.lower()==it:
stack.append(it.upper())
else:
stack.append(it.lower())
print (''.join(stack))
'''
Write a program which swaps letters' case in a sentence. All non-letter characters should remain the same.
Input sample:
Your program should accept as its first argument a path to a filename. Input example is the following
Hello world!
JavaScript language 1.8
A letter
Output sample:
Print results in the following way.
hELLO WORLD!
jAVAsCRIPT LANGUAGE 1.8
a LETTER
'''
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.