blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9a454c277d9a93fe1f1d7d6456f3e626bc0d5615 | AylaGunawan/CP1404 | /prac_05/hex_colours.py | 603 | 4.1875 | 4 | """
CP1404 - Practical 05
Hex Colours
"""
COLOUR_TO_CODE = {"black": "#000000", "beige": "#f5f5dc", "chocolate": "#d2691e", "coral": "#ff7f50",
"darkkhaki": "#bdb76b", "darkorange": "#ff8c00", "darkorchid": "#9932cc", "darksalmon": "#e9967a",
"dimgray": "#696969", "gray": "#bebebe"}
colour_name = input("Enter colour name: ").lower()
while colour_name != "":
if colour_name in COLOUR_TO_CODE:
print(f"{colour_name} is {COLOUR_TO_CODE[colour_name]}")
else:
print("Invalid colour name")
colour_name = input("Enter colour name: ").lower()
| false |
8a45f66a39fee8556fa1aa8fc27170e33034cbdb | alexisbird/BC2repo | /number_guess.py | 2,952 | 4.625 | 5 | """Have the program generate a random int between 1 and 100. Keep it a secret. Ask the user to guess. Tell them if the secret number is higher or lower than their guess. Let them guess until they get it right.
Advanced:
Limit the number of guesses to 5."""
# ***NOTE TO SELF*** if you have the time and desire:
# - Add a quit function
# - Add an option to play again at end of game
# Import built-in Python function randint to generate a random integer
from random import randint
# Randomly generate a secret number between 1 and 100
secret_number = randint(1, 100)
# Make into string to keep things clean, so to speak (easier comparison options, game doesn't break when user enters a letter or word)
secret_number_string = str(secret_number)
# this is just for testing purposes
print(secret_number)
# Establish initial value for user's guess number as 1
guess_number = 1
# Initial print statement to explain the game
print("\nThe computer has randomly selected a number between 1 and 100. Enter a number to guess what it is. You have 5 guesses total. ")
# While loop to limit number of guesses
while guess_number < 5:
# Ask user to guess a number, convert to integer so computer knows it's a number
user_guess = input("\nPlease guess a number. ")
# If statement to determine if user has won
# If statement determines what happens in the event that the user guesses correctly
if user_guess == secret_number_string:
print("That is correct! You win!")
exit()
# Elif statement determines what happens if the user guesses incorrectly
elif user_guess != secret_number_string:
# Variable for remaining guesses so that user knows how many guesses they have left: 5 (max number of guesses) minus the number of the guess that the user is currently on equals the remaining number of guesses
remaining_guesses = 5 - guess_number
# If statement within if statement to specify if guess should be printed plurally or singularly because I'm a weird grammar Nazi like that
# If specifies that it is guesses since it will be plural if the number is greater than 1
# stringify the number so you can concatinate it
if remaining_guesses > 1:
print("Nope. Keep guessing! You have " + str(remaining_guesses) + " guesses left. ")
# Elif specifies that guess is singular when it is 1
elif remaining_guesses == 1:
print("Nope. Keep guessing! You have " + str(remaining_guesses) + " guess left. ")
# Increment number of guesses each time we loop through to limit number of guesses
guess_number += 1
# If statement to account for when user is on the very last guess, guess #5, primarily for the purpose of alerting user if they have completely lost the game
if guess_number == 5:
user_guess = input("\nPlease guess a number. ")
if user_guess == secret_number_string:
print("That is correct! You win!")
else:
print("Incorrect and out of guesses! Game over. You get nothing! You lose! Good day, sir (or madame)! ")
exit()
| true |
f5fbd7c1bad67704b35d81b9cb0d18c5a01dd1c5 | PogramLearningWithPouyan/advanced-python | /video29.py | 445 | 4.125 | 4 | # iterable => list tuple set string
# iterator
# iterate
numlist=[1,2,3,4,5]
# for num in numlist:
# print(num)
# iternum=iter(numlist)
# print(next(iternum))
# print(next(iternum))
# print(next(iternum))
# print(next(iternum))
# print(next(iternum))
list
name='pouyan'
itername=iter(name)
print(next(itername))
print(next(itername))
print(next(itername))
print(next(itername))
print(next(itername))
print(next(itername)) | false |
b5f8ce7fc2f8ee32869a882dd189ce24ad11e8ee | laufei/PythonExample | /2. 反转链表.py | 1,176 | 4.21875 | 4 | # coding: utf-8
# @Time : 2019/7/31 10:26 AM
# @Author : 'liufei'
# @Email : fei.liu@qyer.com
# @Software: PyCharm
'''
假设存在链表 1 → 2 → 3 → Ø,我们想要把它改成 Ø ← 1 ← 2 ← 3。
在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。
在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!
'''
class Node(object):
def __init__(self, data, next=None):
self._val = data
self._next = next
def reverseList(head):
pre = None
cur = head
while cur:
# tmp = cur._next
# cur._next = pre
# pre = cur
# cur = tmp
cur._next, pre, cur = pre, cur, cur._next
return pre
#测试用例
if __name__ == '__main__':
l1 = Node(3)
l1._next = Node(2)
l1._next._next = Node(1)
l1._next._next._next = Node(9)
print (l1._val, l1._next._val, l1._next._next._val, l1._next._next._next._val)
l = reverseList(l1)
print (l._val, l._next._val, l._next._next._val, l._next._next._next._val) | false |
0215cb209db874303eafe410171c442c7d85b0db | popnfreshspk/python_exercises | /connect_four/pt1_piece_and_board.py | 821 | 4.40625 | 4 | # CONNECT 4 Part: 1
#
# This exercise should expand on the TIC-TAC-TOE learning and let you explor
# implementing programs with classes.
#
# The output of your game board should look like the following:
#
# 0 1 2 3 4 5 6
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |_|_|_|_|_|_|_|
# |●|_|_|●|_|_|_|
#
# The challenge here is that you will need to color the pieces to indicate to the
# players which piece has been dropped.
#
# You can use the colorama library to do this: https://pypi.python.org/pypi/colorama
from colorama import Fore, Back, Style
class Piece(object):
def __init__(self, color):
self.piece = '●'
def __str__(self):
return ''
class Board(object):
def __init__(self):
self.board = [
['_']*7 for i in range(6)
]
def __str__(self):
return ''
| true |
f2642ca47db5cbe70990d96919108745009ddc90 | kwy518/Udemy | /BMI.py | 221 | 4.28125 | 4 | weight = input('Please enter your weight(kg): ')
height = input('Please enter your height(cm): ')
height = float(height)
weight = float(weight)
height /= 100
BMI = weight / (height * height)
print('Your BMI is: ', BMI) | true |
6bc1c39d0bfd966c86046b9b2b34af90fc49a7b8 | ocanava/number_guessing_game | /app.py | 1,401 | 4.15625 | 4 | """
Python Web Development Techdegree
Project 1 - Number Guessing Game
--------------------------------
import random
number = random.randint(1, 10)
def start_game():
print("Welcome to the Number Guessing Game!!")
input("Press ENTER to continue...")
Tries = 1
while True:
try:
number = int(input("Pick a number between 1 and 10: "))
number = int(number)
guess_value = 3
except ValueError:
print("Oops! Please enter a valid number.")
Tries = Tries + 1
else:
if guess_value > number:
print("It's Higher! ")
Tries = Tries + 1
continue
elif guess_value < number:
print("It's Lower! ")
Tries = Tries + 1
continue
elif guess_value == number:
Tries = str(Tries)
print("Well done! You guessed it in", Tries + " tries. Game has ended! See you next time! ")
break
start_game()
| true |
23b620af391c84e21d5ed4b5a2617343346ff020 | kumarmj/test | /main.py | 1,002 | 4.1875 | 4 | # Chapter 1: The role of algorithms in Computing
# In this chapter, we will answer these questions
# What are algorithms?
# An algorithm is thus a sequence of computational steps that transform the input into the output
# e.g. let's define sorting problem
# Input: A sequence of n numbers a1, a2,...an.
# Output: Produce a reordering where a1 < a2 < .. < an
nums = [2, 1, 5, 4, 3]
print("Input: ", end='')
print(nums)
print("Problem: Produce ordering where a1 < a2 < .. < an")
print("Output: ", end='')
print(sorted(nums))
# Which algorithm is best for a given application depends on—among other factors—
# - the number of items to be sorted, the extent to which the items are already somewhat sorted, possible restrictions on the item values,
# - the architecture of the computer, and the kind of storage devices to be used: main memory, disks, or even tapes.
# Why is the study of algorithms worthwhile ?
# What is the role of algorithms relative to other technologies used in computers ?
| true |
7346d76a53843db430d118cd4981d0611e0bb3a4 | denisecase/chapstack | /scripts/04-functions.py | 2,616 | 4.125 | 4 | """04-functions.py
This script provides practice working with functions.
It's based on the script 3 - we use functions to make our code more
reusable and easier to maintain.
We add some fun css effects (zoom when we hover).
See index.html - in this example, our html has additional elements
See styles - we add a zoom class to our images with some :hover behavior
"""
from browser import document, console, html
# Define a function to convert a string value to integers
# If it works, return the int
# If it fails, return None
def getIntFromString(s):
try:
x = int(s)
except:
x = None
return x
# Define a function that takes 2 integers and
# returns a string message comparing them
def getCompareMessage(a, b):
if type(a) != int or type(b) != int:
s = f'Oh oh! We could not compare the numbers :(.'
elif a > b:
s = f'Wow! num1 ({a}) is GREATER than num2 ({b}).'
elif a < b:
s = f'Hey! num1 ({a}) is LESS than num2 ({b}).'
else:
s = f'Yay! num1 ({a}) is EQUAL to num2 ({b}).'
return s
# Define a function that returns a new sheep image
def makeSheepImage():
image = html.IMG()
image.src = "images/sheep.png"
image.alt = "one sheep"
image.width = 50
image.height = 50
# Add classes Cwith a capital Class
image.class_name = "zoom"
return image
# Define a callback function (for after an event)
def show4(event):
console.log('You clicked button 4!')
# Compare numbers
num1 = document['input-num1'].value
num2 = document['input-num2'].value
x = getIntFromString(num1)
y = getIntFromString(num2)
document['output4'].text = getCompareMessage(x,y)
# Compare names
name1 = document['input-name1'].value
name2 = document['input-name2'].value
name1len = len(name1)
name2len = len(name2)
secondMessage = f'Your name has {name1len} letters and your friend has {name2len}.'
document['output4-names'].text = secondMessage
# Explain the ranch
ranchMessage = f'Hi {name1}! Hi {name2}! You can store {x*y} sheep on a {x} mi x {y} mi ranch.'
document['output4-ranch-message'].text = ranchMessage
# In this exercise, we've explicitly added the article and br to the html
# Append the sheep
for i in range(0, x*y):
document['output4-ranch-article'] <= makeSheepImage()
# Define a callback function (for after an event)
def moveSheep4(event):
console.log('You clicked on the ranch!')
# make sheep move
# First, bind the btn4 click event to our callback method
document['input-btn4'].bind('click', show4)
# Next, bind the mouseover event to our article
document['output4-ranch-article'].bind('click', moveSheep4) | true |
1d297e99053f2596a3e59364129cedd8a5c35f4d | cnDelbert/Karan-Projects-Python | /Text/Count_Words_in_a_String.py | 826 | 4.5 | 4 | # coding: utf-8
__author__ = 'Delbert'
"""
Count Words in a String - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary.
"""
def count_by_input(inp):
return len(inp.strip().split())
def count_by_file(inp):
f = open(inp, "r").readlines()
cnt = 0
for line in f:
cnt += len(line.strip().split())
return cnt
def chose_mode(mode):
if mode == "i" or mode == "input":
inp = input("Input your string:\t")
print(count_by_input(inp))
elif mode == "t" or mode == "text":
inp = input("Path to text file:\t")
print(count_by_file(inp))
def main():
mode = input("Which one do you want? input(i) or text(t)?")
chose_mode(mode.lower())
if __name__ == "__main__":
main() | true |
b0d3208e3e8599e913dbda7124657ec67e8129e5 | philburling/UndergraduateElectiveModules | /Introduction to Programming -with Python/numbersorter.py | 975 | 4.4375 | 4 | # Filename: numbersorter.py
# Title: Number Sorter
# Function: Sorts 10 numbers entered by the user into descending numerical order
# starting the highest first and ending with the lowest. It then prints the new
# order in a list for the user to see.
# Author: Philip Burling
# Date: 28/04/07
# First the program creates an empty list to store the numbers.
numbers = []
# The counter (variable 'n'), for which number is being entered, is set to '1'
n = 1
# A loop asks the user to enter a number and then adds it to the list. It then
# adds 1 to the counter. It does this until the counter has reached 10, such
# that it repeats the process 10 times.
while n <=10:
number = [input('Enter a number: ')]
numbers = numbers + number
n = n+1
# This section sorts the numbers in the list into ascending numerical order and
# then reverses it to put it in descending order.
numbers.sort()
numbers.reverse()
# The next line displays the list to the user
print numbers
| true |
f19e136c3552317f9445bbeaaff2d407c7ff560f | philburling/UndergraduateElectiveModules | /Introduction to Programming -with Python/OrangutanDave.py | 921 | 4.40625 | 4 | # Filename: OrangutanDave.py
# Title: Dave the Orangutan
# Function: Creates an object (an orangutan called Dave) and gives it the
# co-ordinates (2,2). The program then displays how far (in a straight line)
# 'Dave' is from the point (5,3) where his favourite food is.
# Author: Philip Burling
# Date: 28/04/07
# This line imports the class 'OrangUtan' from the file 'OrangUtan.py' (which
# should be in the same directory) along with its associated functions.
from OrangUtan import *
# This line creates the object 'Dave' of the class 'OrangUtan' and assigns it a
# name, x co-ordinate and y co-ordinate.
Dave = OrangUtan('Dave',2,2)
# This line prints the distance (as the crow flies) that Dave is from the
# location of the food at (5,3). It finds this distance by calling the function
# 'distanceFrom' from the imported rules from the file 'OrangUtan.py'
print 'Dave is', Dave.distanceFrom(5,3), 'units from his food'
| true |
e3dfcbb368b8016dee32ec4d8d72c34a1735fe4b | Shootniky/gb_homework_py | /les2_hw_2/task_3_2.py | 739 | 4.15625 | 4 | """ 3. Пользователь вводит месяц в виде целого числа от 1 до 12.
Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
Напишите решения через list и через dict. """
# with a dict
year = {'зима': [1, 2, 12], 'весна': [3, 4, 5], 'лето': [6, 7, 8], 'осень': [9, 10, 11]}
month = 0
try:
month = int(input('Пользователь вводит месяц числом от 1 до 12: '))
except ValueError as e:
print(e)
for key, value in year.items():
if month in value:
print(f'Ваш месяц относится ко времени года - {key}')
| false |
4da7f5cd5650eb8a60b8d624d25fa0900b2be33c | Shootniky/gb_homework_py | /lesson1_hw1/task_2.py | 810 | 4.4375 | 4 | """2. Пользователь вводит время в секундах. Переведите время в часы,
минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. """
user_date = int(input('Пользователь вводит время в секундах: '))
if user_date > 345600:
print('Пользователь ввёл слишком большое число, за гранью четвёртых суток!!! Программа завершена. ')
quit()
def time(seconds):
hour = seconds // 3600
minute = seconds % 3600 // 60
second = seconds % 3600 % 60
return '{:02d}:{:02d}:{:02d}'.format(hour, minute, second)
time_in = time(user_date)
print(time_in)
| false |
2ad89bf0f243c107cb885fbd06163c50343a9590 | Shootniky/gb_homework_py | /les2_hw_2/task_3.py | 1,256 | 4.34375 | 4 | """ 3. Пользователь вводит месяц в виде целого числа от 1 до 12.
Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
Напишите решения через list и через dict. """
# with a list
month = 0
months = ['Декабрь', 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь',
'Ноябрь']
try:
month = int(input('Пользователь вводит месяц числом от 1 до 12: '))
except ValueError as e:
print(e)
winter = months[0:3]
spring = months[3:6]
summer = months[6:9]
autumn = months[9:12]
if 2 < month < 6:
print('Ваш месяц весенний', spring)
elif month == 6 and month < 9:
print('Ваш месяц летний', summer)
elif month == 9 and month < 12:
print('Ваш месяц осенний', autumn)
elif month == 1 or month == 2 or month == 12:
print('Ваш месяц зимний', winter)
elif month > 12 or month < 1 and month == int:
print('Вы ввели числа за пределами периода года 1-12!')
| false |
ef4893b9a6ebacda80a48219f20fcb2df250941e | malekmahjoub635/holbertonschool-higher_level_programming-2 | /0x07-python-test_driven_development/4-print_square.py | 685 | 4.46875 | 4 | #!/usr/bin/python3
"""
Module to print a square
"""
def print_square(size):
"""
a function that prints a square with the character #.
Args:
size(int): size of the square
Raises:
TypeError: if size is not integer
ValueError: if size less than 0
Returns:
a printed square
"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
if isinstance(size, float) and size < 0:
raise TypeError("size must be an integer")
for i in range(0, size):
for j in range(0, size):
print("#", end="")
print()
| true |
30102d891dde0e518c406b0d0341bfc061ef3298 | malekmahjoub635/holbertonschool-higher_level_programming-2 | /0x0B-python-input_output/1-write_file.py | 363 | 4.34375 | 4 | #!/usr/bin/python3
""" write file Module """
def write_file(filename="", text=""):
"""
write file function
Args:
filename(string): the given file name
text(string): the text
Returns:
number of characters written.
"""
with open(filename, 'w', encoding="UTF8") as f:
f.write(text)
return len(text)
| true |
c39cb788505ab8251c84bbc46910442838726703 | 1296279026/Pyxuexi | /DiYi.py | 667 | 4.40625 | 4 | #第一个代码
#print('hello world!')
#print(6+6)
#导入别人写的乌龟
import turtle
#创建一个乌龟
my_turtle=turtle.Turtle()
#让乌龟有个乌龟的形状
my_turtle.shape("turtle")
#乌龟向前走100步
my_turtle.forward( 300 )
#让乌龟右转90度
my_turtle.right(90)
#乌龟再向前走100步
my_turtle.forward( 300 )
#让乌龟右转90度
my_turtle.right(90)
#乌龟再向前走100步
my_turtle.forward( 300 )
#让乌龟右转90度
my_turtle.right(90)
#乌龟再向前走100步
my_turtle.forward( 300 )
turtle.mainloop()
name="Chenming"
print(name)
print(name[5])
print(len(name))
print(name+'zhenbang')
print(name[0:8])
print((name+"\n")*2)
| false |
87c0434acc2026da30d236311857734a702fbca2 | amanlalwani007/important-python-scripts | /insertion sort.py | 482 | 4.125 | 4 | def insertionsort(arr):
if len(arr)==1:
print("already sorted",arr)
return
else:
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and arr[j]>key:
arr[j+1]=arr[j]
j=j-1
arr[j+1]=key
print("sorted array is",arr)
return
#cards game
arr=[]
print("Enter size of array")
n=int(input())
print("enter elements")
for i in range(0,n):
k=int(input())
arr.append(k)
insertionsort(arr) | false |
c068b8ca7d7bb252bbdd37720db7b9ebeff4f60c | ananya-byte/Code-for-HacktoberFest-2021 | /Intermediate/Python/second_highest.py | 588 | 4.21875 | 4 | def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def main():
l = [4,3,1,5,2] #given list
l = bubbleSort(l)
n = len(l)
print("Second highest element:",str(l[n-2]))
main()
| true |
b838bb47b7f9a0f56fe6dadc188a0ad8a9446f73 | CivicTesla/Teacher-Stone-s-Data-Structure-Lesson | /Notes/01-Basic/src/Fraction.py | 1,484 | 4.34375 | 4 | # 1. how to define a class
# 2. show function definition in class and out of class
# 3. show main function
# 4. the meaning of self
# When defining an instance method,
# the first parameter of the method should always be self
# (name convension from the python community).
# The self in python represents or points the instance which it was called.
# Explain it via Example (object called the function, the address of the
# instance will automatically passed to self)
class Fraction:
def __init__(self,top,bottom):
self.num = top
self.den = bottom
def show(self):
print(self.num,"/",self.den)
def __str__(self):
return str(self.num)+"/"+str(self.den)
def __add__(self,otherfraction):
newnum = self.num*otherfraction.den + self.den*otherfraction.num
newden = self.den * otherfraction.den
common = gcd(newnum,newden)
return Fraction(newnum//common,newden//common)
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
# calculate greatest common divisor
def gcd(m,n):
while m%n != 0:
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
if __name__ == '__main__':
x = Fraction(1,2)
y = Fraction(2,3)
x.show()
y.show()
print(x.__str__())
z = x.__add__(y)
z.show()
result = x.__eq__(y)
print(result)
| true |
0f84bb21c8148a79a337527f89d0afb60953a72b | ellojess/coding-interview-practice | /LeetCode/two-sums.py | 1,066 | 4.125 | 4 | '''
Prompt:
Given an array of integers, return indices of the two
numbers such that they add up to a specific target.
You may assume that each input would have
exactly one solution, and you may not use the same
element twice.
Summary:
Find the indices of two numbers that add up to a specific target.
Examples:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Input: [2,7,11,15, 3], Target: 10
Output: [1,4]
- track the values and indeces of every item in a list
- store values as keys in a dictionary
- loop through the array and see if the difference between that
value and the target is a key within the dictionary,
- continue until an array value and key add up to the target
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numsDict = {}
for index, value in enumerate(nums):
difference = target - value
if difference in numsDict:
return [numsDict[difference], index]
numsDict[value] = index | true |
d2ba77f5316776a5acee116a7931a7d5aae92bbf | codesbyHaizhen/show-circle-and-rectangle-with-self-defined-modul | /ModulGeometry/circle.py | 860 | 4.21875 | 4 | # Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='red'):
self.radius = radius
self.color = color
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
def drawCircle(self):
# this method shows the circle graph
import matplotlib.pyplot as plt
circle = plt.Circle((0, 0), radius=self.radius, fc=self.color)
# create a object reference to the circle, not the image of the circle itself
plt.gca().add_patch(circle)
# gives a reference to the current axes and adds the shape to the graph
plt.axis('scaled')
# gives appropriate scaling that you specify for the shape. the default value is 1.0 vertivally and horizontally
plt.show()
# show the circle graph | true |
4b779bed75cf8b9f1374f3d6df747980c222556c | ksripathi/python-programmes | /basics/month.py | 626 | 4.5625 | 5 | '''
This programme is about computing month number based on user input
'''
month=input("Enter the month name e.g January")
if month == "Janauary":
print("1")
elif month == "Febraury":
print("2")
elif month == "March":
print("3")
elif month == "April":
print("4")
elif month == "May":
print("5")
elif month == "June":
print("6")
elif month == "July":
print("7")
elif month == "August":
print("8")
elif month == "September":
print("9")
elif month == "October":
print("10")
elif month == "November":
print("11")
elif month == "December":
print("12")
else:
print("Please enter valid month name")
| false |
98cc1941b3e421126a3a7b1a77ac366133761591 | andreiturcanu/Data-Structures-Algorithms-Udemy-Course | /Selection Sort Algorithm Implementation - Project.py | 631 | 4.25 | 4 | #Write Selection Sort Algorithm; Ascending Order
def selectionsort (array):
for i in range(len(array) - 1):
#identify index to be equal to i
index = i
#1 through length of array -1
for j in range (i+1, len(array),1):
if array [j] < array [index]:
#we find smallest item in that given array
index = j
if index != i:
temp1 = array[index]
temp2 = array[i]
array[index]=temp2
array[i]=temp1
return array
c = [-1,-3,-2,0]
a = [5,2,1,7,6,8,8,0]
b = [4,3,2,1,100,45,10,99,101,4.5]
print (selectionsort(a))
print (selectionsort(b))
print (selectionsort(c)) | true |
72269a40897df9c8e829815aa805dd57c923d04b | andreiturcanu/Data-Structures-Algorithms-Udemy-Course | /Quick Sort Algorithm Implementation - Project.py | 1,108 | 4.15625 | 4 | #Write Quick Sort Algorithm; Ascending Order
def quicksort (array, low, high):
if low >= high:
return
#partition array
#select middle item in array
piv_index = (low+high)//2
#sort
temp1 = array[piv_index]
temp2 = array[high]
array[piv_index]=temp2
array[high]=temp1
i = low
#make sure all items smaller than piv, wil be on left; all items greater than piv, will be on the right
for j in range(low,high,1):
if array[j] <= array[high]:
#sort
temp3 = array[i]
temp4=array[j]
array[i]=temp4
array[j]=temp3
i = i + 1
#sort. Divide and conquer
temp5 = array[i]
temp6 = array[high]
array[i]=temp6
array[high]=temp5
#make sure to make i index of the piv
piv_index=i
#divide and conquer algorithm and that's why it can be implemented with recursive calls
#partition with piv, creates threshold
quicksort(array,low, piv_index-1)
quicksort(array, piv_index+1,high)
a = [-2,-1,0,1,0,-1,-2]
b= [-5,3,1,-10,-20,-30,-2,-7,0,1,-1,7,10,13,-13,7,-12]
quicksort(a,0,len(a)-1)
quicksort(b,0,len(b)-1)
print(a)
print(b)
| true |
3a9c797ad3aeb48b52c81298eae76973f2211fd9 | drvinceknight/rsd | /assets/code/src/is_prime.py | 363 | 4.25 | 4 | """
Function to check if a number is prime.
"""
def check(N):
"""
Test if N is prime.
Inputs:
- N: an integer
Output:
- A boolean
"""
potential_factor = 1
while potential_factor < N / 2:
potential_factor = potential_factor + 1
if (N % potential_factor == 0):
return False
return True
| true |
1c494fdac791749392e673dff546d3b1a6008c48 | juliorhode/Python | /excepciones/1-excepciones.py | 1,192 | 4.21875 | 4 | # Las excepciones son errores en tiempo de ejecucion del programa. La sinstaxis del codiggo es correcta pero
# durante la ejecucion ha ocurrido "algo inesperado".
def suma(num1, num2):
return num1+num2
def resta(num1, num2):
return num1-num2
def multiplica(num1, num2):
return num1*num2
def divide(num1, num2):
try:
return num1/num2
except ZeroDivisionError:
print("No se puede dividir entre 0")
return "Operacion erronea"
while True:
try:
op1 = (int(input("Introduce el primer numero: ")))
op2 = (int(input("Introduce el segundo numero: ")))
break
except ValueError:
print("Los valores introducidos no son correctos. Intente nuevamente")
operacion = input("Introduce la operacion a realizar (suma, resta, multiplica, divide): ")
if operacion == "suma":
print(suma(op1, op2))
elif operacion == "resta":
print(resta(op1, op2))
elif operacion == "multiplica":
print(multiplica(op1, op2))
elif operacion == "divide":
print(divide(op1, op2))
else:
print("Operacion no contemplada")
print("Operacion ejecutada. Continuacion de ejecucion del programa")
# Captura o control de excepcion | false |
662fb93b5d859097b4bf55c34343989c9ea469fa | TudorMaiereanu/Algorithms-DataStructures | /mergesort.py | 744 | 4.3125 | 4 | # Mergesort algorithm in Python
import sys
# function to be called on a list
def mergesort(unsortedList):
mergesortIndex(unsortedList, 0, len(A)-1)
def mergesortIndex(unsortedList, first, last):
if first < last:
middle = (first + last)//2
mergesortIndex(unsortedList, first, middle)
mergesortIndex(unsortedList, middle+1, last)
merge(unsortedList, first, middle, last)
def merge(unsortedList, first, middle, last):
left = unsortedList[first:middle+1]
right = unsortedList[middle+1:last+1]
left.append(sys.maxsize)
right.append(sys.maxsize)
i = j = 0
for k in range(first, last+1):
if left[i] <= right[j]:
unsortedList[k] = left[i]
i += 1
else:
unsortedList[k] = right[j]
j += 1
| true |
39a2bd9408657fbf40b7a20fa5d0c1b089cdeea9 | jesseulundo/basic_python_coding | /nested_data_structure.py | 1,711 | 4.5 | 4 | """
Create a list nested_list consisting of five empty lists
"""
nested_list = [[], [], [], [], []]
print(nested_list)
print("Nested_list of length 5 whose items are themselves lists consisting of 3 zeros")
print("===============================================================================")
n_nested_list = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
print(n_nested_list)
print("===============================================================================")
print("list comprehansion of 3 zeroes")
print("==============================")
zero_list = [0 for dummy_idx in range(3)]
l_c_nested_list = [[0 for dummy_idx1 in range(3)] for dummy_idx2 in range(5)]
print(zero_list)
print(l_c_nested_list)
print("===============================================================================")
print("Select a specific item in a nested list")
print("==========================================")
n_l_c_nested_list = [[col + 3 * row for col in range(3)] for row in range(5)]
print(n_l_c_nested_list[2][1])
print("===============================================================================")
print("Create a list list_dicts of 5 empty dictionaries")
print("================================================")
list_dicts = [{}, {}, {}, {}, {}]
print(list_dicts)
print("===============================================================================")
print("Function that returns a list consisting of copies of my dict")
print("============================================================")
def dict_copies(my_dict, num_copies):
answer = []
for idx in range(num_copies):
answer.append(dict(my_dict))
return answer
print(dict_copies({},5))
| true |
0c2cfc4554e2444d2bee517d03be6d0d4e9be96e | axtell5000/working-with-python | /basics-1.py | 873 | 4.125 | 4 | # Fundamental Data types
int
float
bool
str
list
tuple
set
dict
# Classes - custom data type
# Specialized data types - external packages
None
# int and float
print(type(3 + 3))
print(type(2 * 8))
print(type(2 / 8))
print(2 ** 2) # 4
print(4 // 2) # rounds down to integer
print(6 % 4) # modular remainder
# Math fnctions
print(round(10.5))
print(round(10.6))
print(round(11.2))
print(abs(-200)) # 200
print(bin(8)) # 0b1000 - prints binary
print(int("0b1000", 2)) # 8
# Variables
user_iq = 150 # snake case, must start with underscore or letter, case sensitive
a, b, c, d = 5, 10, 15, 20 # to assign multiple variables at once
# constants
PI = 3.141
# Expression + Statement
user_age = user_iq / 5 # user_iq / 5 is an expression, whole line is a statement
# Augmented Assignment Operator, like i++ in loops
some_num = 5
some_num += 10
print(some_num)
| true |
ac1f79328c2c79bc5cab0ebc059821acb7817321 | guillempalou/scikit-cv | /skcv/multiview/util/synthetic_point_cloud.py | 1,926 | 4.15625 | 4 | import numpy as np
def random_sphere(N, radius, center=None):
"""
Generates N points randomly distributed on a sphere
Parameters
----------
N: int
Number of points to generate
radius: float
Radius of the sphere
center: numyp array, optional
center of the sphere. (0,0,0) default
Returns
-------
Array (3, N) with the points
"""
u = 2*np.random.random(N)-1
theta = 2*np.pi*np.random.random(N)
points = np.array((radius*np.sqrt(1-u**2)*np.cos(theta),
radius*np.sqrt(1-u**2)*np.sin(theta), radius*u))
if center is not None:
c = np.repeat(center, N)
c = np.reshape(c, (3, N))
points += c
return points
def random_ball(N, radius, center=None):
"""
Generates N points randomly distributed on a ball
x^2+y^2+z^y <= 1
Parameters
----------
N: int
Number of points to generate
radius: float
Radius of the sphere
Returns
-------
Array (3, N) with the points
"""
r = np.random.random(N)
x = np.random.normal(0, 1, (3, N))
norm = np.linalg.norm(x, axis=0)
points = radius * np.power(r, 1./3.) * x/norm
if center is not None:
c = np.repeat(center, N)
c = np.reshape(c, (3, N))
points += c
return points
def random_cube(N, size, center=None):
"""
Generates N points randomly distributed on cube
Parameters
----------
N: int
Number of points to generate
size: float
Size of the side of the cube
Returns
-------
Array (3, N) with the points
"""
x = size*np.random.random((3, N)) - 0.5*size
face = np.random.randint(0, 3, N)
side = 2*np.random.randint(0, 2, N)-1
x[face, np.arange(0, N)] = (0.5*size)*side
if center is not None:
c = np.repeat(center, N)
c = np.reshape(c, (3, N))
x += c
return x | true |
00882283a9a01dfdbbcc7961ce471ae1046fbc35 | Hol7/100_Days_Challenge | /Day1.py | 664 | 4.25 | 4 | print("Day 1 - Python Print Function ")
print("The function is declared like this:")
print("print('what to print')")
# Debug and fix Exercise
print("Day 1 - String Manipulation")
print("String Concatenation is done with the" "+" "sign.")
print("e.g print('Hello'+'world')")
print("New lines can be created with a backslsn an n.")
# First idea input function
name = input("what is your name?")
print("my name is:", name)
# Secon idea input function
print("Bonjour" + input("Quelle est ton nom?"))
# get the length of a str / taille d'une chaine de charactere
name = input("what is your name? ")
print("my name is:", name)
taille = len(name)
print(taille)
| true |
8bf9e3ac8bb085ac80dc605736d46530c63287c6 | amarendar-musham/Devops | /class_OOPS3.py | 1,020 | 4.28125 | 4 | ## <<v1>> not completed
class person:
def __init__ (self,name,age):
self.name=name
self.age=age
print("name is {} ; and age is {} \n".format(self.name,self.age))
o1=person("ad",3)
## inheritance
class teacher(person):
def printing(self,name,age):
person.__init(self,name,age)
## here no def is defined in teacher class
## inheritance happened
## calling the def in parent class
## person.__init does that
ot=teacher("google",66)
#### another script----- OVERLOADING
## __str__ is used to print the object directly <<v1>>
## u can print it by print(object)
class parent:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
print("name is: {} \n age is: {}".format(self.name,self.age))
p1=parent("amar",11)
class child(parent):
def __init__(self,name,age,sub):
parent.__init__(self,name,age)
self.sub=sub
def __str__(self):
parent.__str__(self)
print("\n sub: {}".format(self.sub))
k1=child("amar",22,"science")
print(k1) ### <<v1>>
| false |
9df8f7a84cb750453653d64b6c6b8c48b6cb793a | naveenshandilya30/Common-Modules-in-Python | /Assignment_8.py | 883 | 4.21875 | 4 | #Question 1
"""A time tuple is the usage of a tuple (list of ordered items/functions) for the ordering and notation of time."""
#Question 2
import datetime,time
print (time.strftime("%I:%M:%S"))
#Question 3
import datetime,time
print ("Month:",time.strftime("%B"))
#Question 4
import datetime,time
print ("Day:",time.strftime("%A"))
#Question 5
import datetime
day=datetime.date(2021,1,11)
print(day.strftime("%A,%d"))
#Question 6
import datetime,time
print(time.asctime(time.localtime()))
#Question 7
import math
from math import factorial
num=int(input("Enter the number: "))
n=factorial(num)
print(n)
#Question 8
import math
from math import gcd
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
print(math.gcd(a,b))
#Question 9
import os
print(os.getcwd()) # current working directory
print(os.environ) #user environment
| true |
173f56f7ae89501528eba25bacd5601ca3a2723e | Sameer2898/Data-Structure-And-Algorithims | /Placement Prepration/Mathmetics/prime_num.py | 555 | 4.125 | 4 | def isPrime(N):
if N <= 1:
return False
if N <= 3:
return True
if (N % 2 == 0 or N % 3 == 0):
return False
i = 5
while(i * i <= N):
if (N % i == 0 or N % (i + 2) == 0):
return False
i += 6
return True
def main():
T = int(input('Enter the number of test cases:- '))
while T > 0:
num = int(input('Enter a number:- '))
if isPrime(num):
print('Yes')
else:
print('No')
T -= 1
if __name__ == "__main__":
main() | false |
334e3b803269c9bd6680449731217a8808e7503c | Sameer2898/Data-Structure-And-Algorithims | /Placement Prepration/Stack/reverse_a_string.py | 434 | 4.125 | 4 |
def reverse(string):
stack = []
for ch in string:
stack.append(ch)
reverse = ''
while len(stack):
reverse += stack.pop()
return reverse
if __name__=='__main__':
t = int(input('Enter the number of test cases:- '))
for i in range(t):
str1 = input('Enter the string:- ')
print(f'The string is:- {str1}.')
print(f'The reverse of the string is:- {reverse(str1)}.') | true |
b9f4adeebf8aaad1e795d00c091e69a4d018dbdc | zhangzhentctc/crawl_hkexnews | /samples/single_select.py | 2,046 | 4.4375 | 4 | from tkinter import *
# This is a demo program that shows how to
# create radio buttons and how to get other widgets to
# share the information in a radio button.
#
# There are other ways of doing this too, but
# the "variable" option of radiobuttons seems to be the easiest.
#
# note how each button has a value it sets the variable to as it gets hit.
class Test(Frame):
def printit(self):
print("hi")
def createWidgets(self):
self.flavor = StringVar()
self.flavor.set("chocolate")
self.radioframe = Frame(self)
self.radioframe.pack()
# 'text' is the label
# 'variable' is the name of the variable that all these radio buttons share
# 'value' is the value this variable takes on when the radio button is selected
# 'anchor' makes the text appear left justified (default is centered. ick)
self.radioframe.choc = Radiobutton(
self.radioframe, text="Chocolate Flavor",
variable=self.flavor, value="chocolate",
anchor=W)
self.radioframe.choc.pack(fill=X)
self.radioframe.straw = Radiobutton(
self.radioframe, text="Strawberry Flavor",
variable=self.flavor, value="strawberry",
anchor=W)
self.radioframe.straw.pack(fill=X)
self.radioframe.lemon = Radiobutton(
self.radioframe, text="Lemon Flavor",
variable=self.flavor, value="lemon",
anchor=W)
self.radioframe.lemon.pack(fill=X)
# this is a text entry that lets you type in the name of a flavor too.
self.entry = Entry(self, textvariable=self.flavor)
self.entry.pack(fill=X)
self.QUIT = Button(self, text='QUIT', foreground='red',
command=self.quit)
self.QUIT.pack(side=BOTTOM, fill=BOTH)
def __init__(self, master=None):
Frame.__init__(self, master)
Pack.config(self)
self.createWidgets()
if __name__ == '__main__':
test = Test()
test.mainloop() | true |
26a10b42641935713f2acf04983d20656f4db2dd | AchaRhaah/prime-numbers | /main.py | 225 | 4.15625 | 4 | n=int(input("enter a number:"))
is_prime=True
for i in range(1,n):
if n%i==0:
is_prime==False
if is_prime==True:
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")
| false |
5437ea12e15311eddce36aa4088a9836d49fdb1a | Ananth3A1/Hkfst2k21 | /calculatorOfGrades.py | 1,131 | 4.3125 | 4 | # program that requests entry with a student's name,
# after entry enter 10 student grades (all must be entered by the program user)
# and after having the grade list for the student show at the end of the program,
# the student's average, the maximum grade, the minimum grade, the first and the last grade assigned to the student.
def get_last_grade(grades):
print(f'The last assign grade was {grades[-1]}')
def get_first_grade(grades):
print(f'The first assign grade was {grades[0]}')
def get_min_grade(grades):
print(f'The minimum grade was {min(grades)}')
def get_max_grade(grades):
print(f'The minimum grade was {max(grades)}')
def get_prom_grade(grades):
print(f'The average grade was {round(sum(grades)/ len(grades), 2)}')
while(1):
grades = []
name = str(input('\nInsert the student name: '))
for i in range(11):
x = int(input("Insert the grades for this student: "))
grades.append(x)
print(f"\nThe grades of {name} are: ")
get_prom_grade(grades)
get_max_grade(grades)
get_min_grade(grades)
get_first_grade(grades)
get_last_grade(grades) | true |
c15cf2aade883ded4b3257a30d1fc2756a46cd20 | gui-akinyele/python_mundo_1_curso_em_video | /Desafios/Desafios_22_27.py | 2,306 | 4.46875 | 4 | """ Exercício 22:
Crie um programa que leia o nome completo de uma pessoa e mostre:
– O nome com todas as letras maiúsculas e minúsculas.
– Quantas letras ao todo (sem considerar espaços).
– Quantas letras tem o primeiro nome.
nome = str(input('Digite seu nome: ')).strip()
espaco = (nome.count(' '))
primeiro = nome.find(' ')
print('Analisando seu nome...')
print(f'Seu nome em maiuscúlas é ... {nome.upper()}')
print(f'Seu nome em minuscúlas é ... {nome.lower()}')
print(f'O total de letra no nome é ... {len(nome) - espaco}')
print(f'Seu primeiro nome tem ... {primeiro} letras') """
""" Exercício 23:
Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
num = int(input('Digite um numero de 0 a 9999: '))
und = num // 1 % 10
dez = num // 10 % 10
cen = num // 100 % 10
mil = num // 1000 % 10
print(f'Analisando o número {num} ....')
print(f'Unidade: {und}')
print(f'Dezena: {dez}')
print(f'Centena: {cen}')
print(f'Milhar: {mil}') """
""" Exercício 24:
Crie um programa que leia o nome de uma cidade diga se ela começa ou não com o nome “SANTO”.
cidade = str(input('Qual a cidade você nasceu? ')).strip()
print(cidade[:5].upper() == 'SANTO') """
""" Exercício 25:
Crie um programa que leia o nome de uma pessoa e diga se ela tem “SILVA” no nome.
nome = str(input('Qual seu nome completo? ')).strip()
print(f'Seu nome tem Silva?', 'SILVA' in nome.upper())"""
""" Exercício 26:
Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”,
em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
frase = str(input('Digite uma frase: ')).upper().strip()
print(f'A letra A aparece {frase.count("A")} vezes na sua frase.')
print(f'A primeira letra A aparece na posição {frase.find("A")+1}')
print(f'A primeira letra A aparece na posição {frase.rfind("A")+1}')"""
""" Exercício 27:
Faça um programa que leia o nome completo de uma pessoa,
mostrando em seguida o primeiro e o último nome separadamente.
nome = str(input('Digite seu nome completo: ')).strip()
nome_aux = nome.split()
print('Muito prazer em te conhecer!')
print(f'Seu primeiro nome é {nome_aux[0]}')
print(f'Seu último nome é {nome_aux[len(nome_aux)-1]}')"""
| false |
506e3d63c06c48166bb57894ee5f85892699cdef | acctwdxab/project-4b | /fib.py | 420 | 4.125 | 4 | # Dan Wu
# 10/19/2020
# To create a function that takes a positive integer parameter and returns the number at that position of the Fibonacci sequence.
def fib(num):
"""The fib function returns the positive number at the position of the fibonacci sequence."""
first_num, second_num = 0 , 1
for i in range ( num ) :
first_num , second_num = second_num , first_num + second_num
return first_num
| true |
7b29f544f5f3d581af92347194d4da2d9fcae53a | Anna-Pramod/LeetCode_Solutions | /isomorphic_strings.py | 1,909 | 4.125 | 4 | #Given two strings 'str1' and 'str2', check if these two strings are isomorphic to each other.
#Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 while preserving the order.
#Note: All occurrences of every character in ‘str1’ should map to the same character in ‘str2’
#User function Template for python3
from collections import Counter
class Solution:
#Function to check if two strings are isomorphic.
def areIsomorphic(self,str1,str2):
l1 = list(Counter(str1).values())
l2 = list(Counter(str2).values())
l1.sort()
l2.sort()
a=[]
d={}
i=0
if l1 == l2:
while (i<len(str1)):
a.append([str1[i],str2[i]])
i+=1
for j in a:
if j[0] in d:
d[j[0]].append(j[1])
else:
d[j[0]] = [j[1]]
for c in (d.values()):
if len(c) != 1:
if c.count(c[0])==len(c):
continue
else:
return 0
return 1
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
from collections import defaultdict
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__=='__main__':
t = int(input())
for i in range(t):
s=str(input())
p=str(input())
ob = Solution()
if(ob.areIsomorphic(s,p)):
print(1)
else:
print(0)
# } Driver Code Ends
# Correct Answer.Correct Answer
# Execution Time:0.27
| true |
e0e1f4f3272c7ecbf5e59d89f6a1ba4112d1de0c | baymer2600/python_challenges | /divisor.py | 358 | 4.1875 | 4 | #Practice Program
#Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
user_input = input("Please provide a number: ")
def divisor(number):
a = []
x = number
while x > 0:
if number % x == 0:
a.append(x)
x -= 1
return(a)
print(divisor(int(user_input))) | true |
6c859b128b1b5fcfb37dfcdc152841d7b791043e | usmanwardag/prep | /5_twos_complement.py | 1,666 | 4.3125 | 4 | # Why do we need 2's complement?
# https://www.youtube.com/watch?v=lKTsv6iVxV4
#
# Two's complement is used to store signed numbers.
#
# How should be store signed numbers in bits?
# One idea is to assign the highest bit 0 or 1
# depending on whether the number is +ve or -ve.
#
# This idea has two problems.
# 1- There are two numbers to store 0 (1000 and 0000).
# 2- We can't use binary operations to add, multiply etc!
#
# To address these problems, we can use two's complement
# format of representing signed numbers.
#
# The intuitive idea behind two's complement is that if
# we have 2^N space, then the upper half stores negative
# and the lower half positive numbers.
#
# Concretely, the two's complement of an N-bit number is
# defined as its complement with respect to 2^N, i.e., the
# sum of a number and its two's complement is 2^N.
#
# Two's complement is achived by (i) reversing bits, and
# (ii) adding 1.
#
# With this representation, we can perform binary operations
# as normal, and we have a single representation for zero.
def twos_complement(num, N):
if num == 0:
return 0
else:
return (1 << N) - num
def recover_twos_complement(num, N):
# Check if signed bit (highest bit) is set
if (num & (1 << N-1)):
return num - (1 << N)
else:
return num
num = 5
N = 3
print(num, twos_complement(num, N))
assert num + twos_complement(num, N) == pow(2, N)
print(0, twos_complement(0, 3))
assert 0 == twos_complement(0, 3)
num = 5
N = 4
print(num, twos_complement(num, N), recover_twos_complement(twos_complement(num, N), N))
assert recover_twos_complement(twos_complement(num, N), N) == -num
| true |
c72b198242f1fa333a728ee426e5ebe80d4a1cde | jackpetersen3/leap_year | /leapYear2.py | 579 | 4.125 | 4 | quit1 = 0
while quit1 == 0:
year = input("Enter a year: ")
try:
year = int(year)
except:
print("input must be an integer")
break
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year\n")
else:
print(year, "is not a leap year\n")
else:
print(year, "is a leap year\n")
else:
print(year, "is not a leap year\n")
quit1 = input("To enter another year press 0, to quit press 1: ")
quit1 = int(quit1) | false |
d9599b68b38c8ad91487a7ce2246f5eaeb712143 | AlexKovyazin/python_basic | /Lesson_4/Task_7.py | 802 | 4.125 | 4 | from functools import reduce
def multiplication(stop_num):
"""Перемножет все элементы списка и выводит результат умножения"""
# то же самое, что в задаче № 5, но импортировать только функцию multiplication не получилось -
# - выдавал ещё и результат всей задачи № 5.
# Надо сделать условие с name и __main__?
result_list = []
for i in range(1, stop_num + 1):
result_list.append(i)
return reduce(lambda x, y: x * y, result_list)
def fact_yield(stop_num):
for element in (multiplication(num) for num in range(1, stop_num + 1)):
yield element
for el in fact_yield(20):
print(el)
| false |
a677c3a3844460845066f20dc9bd3766955e4eb7 | OmarThinks/numpy-project | /learning/A)Intro/09_join.py | 617 | 4.125 | 4 | import numpy as np
array1 = [[1,2],[3,4]]
array2 = [[5,6],[7,8]]
print("Concatenate")
print("_________")
array3_0 = np.concatenate((array1,array2), axis=0)
print(array3_0)
"""
[[1 2]
[3 4]
[5 6]
[7 8]]
"""
array3_1 = np.concatenate((array1,array2), axis=1)
print(array3_1)
"""
[[1 2 5 6]
[3 4 7 8]]
"""
print("")
print("Stack")
print("_________")
array1 = [1,2, 3,4]
array2 = [5,6,7,8]
array3_0 = np.stack((array1,array2), axis=0)
print(array3_0)
"""
[[1 2 3 4]
[5 6 7 8]]
"""
array3_1 = np.stack((array1,array2), axis=1)
print(array3_1)
"""
[[1 5]
[2 6]
[3 7]
[4 8]]
"""
| false |
1679b4e34a398a81aa293ff2c8471d151d8f5fc4 | Shamyukthaaaa/Python_assignments | /fruits_set.py | 1,334 | 4.1875 | 4 | # To Be Implemented Set methods
fruits=set()
num=int(input("Enter the number of elements to be present in the set: "))
for i in range(num):
fruits_set=input("Enter fruit {} :".format(i+1))
fruits.add(fruits_set)
print(fruits)
#add method
print(fruits.add("papaya"))
#update method
veggies=["potato","ladiesfinger","beans","tomato"]
fruits.update(veggies)
print(fruits)
#len method
print(len(fruits))
#max method
print(max(fruits))
#min method
print(min(fruits))
vegetables={"tomato","carrot","yam","potato","raddish"}
#copy method
set1={}
set1=fruits.copy()
print("new set is: ",set1)
#union method
print(vegetables.union(fruits))
print(fruits.union(veggies))
#intersection method
print(fruits.intersection(vegetables))
#difference method
print(vegetables.difference(fruits))
print(fruits.difference(vegetables))
#symmetric_difference method
print(vegetables.difference_update(fruits))
print(fruits.difference_update(vegetables))
#isdisjoint method
print(fruits.isdisjoint(vegetables))
#issubset method
print(vegetables.issubset(fruits))
#issuperset method
print(fruits.issuperset(vegetables))
#pop method
fruits.pop()
print(fruits)
#remove method
fruits.remove("apple")
#discard method
vegetables.discard("tomato")
#clear method
vegetables.clear()
#del method
del fruits
| true |
47ad5edd172c6f1951efbd159b398cf090eadfbc | minddrummer/leetcode | /single questions/SearchInsertPosition.py | 909 | 4.15625 | 4 | # Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
# You may assume no duplicates in the array.
# Here are few examples.
# [1,3,5,6], 5 2
# [1,3,5,6], 2 1
# [1,3,5,6], 7 4
# [1,3,5,6], 0 0
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums[0] > target:
return 0
for i in range(len(nums)-1):
if nums[i] == target:
return i
if nums[i] < target and nums[i+1] > target:
return i+1
if nums[-1] == target:
return len(nums)-1
return len(nums)
if __name__ == '__main__':
sk = Solution()
print sk.searchInsert([0,1,2],3)
print sk.searchInsert([0,1,4],3)
print sk.searchInsert([0,1,4],-3)
| true |
ab2eee9e92e20cae6d71e6ccd6c57bfe64be3de0 | Deependrakumarrout/Small-Assignment | /Simple project/cheak prime number.py | 2,714 | 4.3125 | 4 |
#Making a function to restart
def restart():
try:
num=int(input("Enter a number:"))
if num>1:
for i in range (2,num):
if (num%i)==0:
print(num,"is not a prime number..")
print(i,"x",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
except:
print("You have insert a invalid value..")
data=" "
while data != 'yes' or 'no':
data = str(input("Do you want to restart again:"))
if data=='yes'.lower():
print("processing..")
restart()
break
elif data=="no".lower():
print("Dont want to do restart")
break
else:
print("Invalid input")
restart()
#Simple prime program
'''num=int(input("Enter a number to detect prime:"))
if num>=1:
for i in range (2,num):
if (num%i)==0:
print(num,"is not a prime number")
print(i,"x",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")'''
#A even or odd number
'''num=int(input("Enter a number:"))
if num%2:
print(num,"its a odd number")
else:
print(num,"is a even number")'''
'''t=(5,'program',1+3)
print("t[1]=",t[0])
print("t[0:3]=",t[0:3])'''
#finding prime number
'''while True:
num=input("Enter a number to find the prime to not:")
if num!='q' and num>=str('1'):
num = int(num)
for i in range(2,num):
if (num%i)==0:
print(num,'is not a prime number')
print(i,'x',num//i,'is',num)
break
else:
print(num,'is a prime number')
else:
print("User want to stop the program\n\n")
break'''
# Explain the prime number
#we will take 1 which is not a prime number in if statement
#for to repete it to cheak the number which is divisiable by 2,num
#And then the number to put the reminder by giving the (%) opeator to get the reminder
#if it get 0 then it will display is not a prime number
#or if it wil show the 1 of which will be the prime number
#break
'''
num1=int(input("Enter a number:"))
if num1>1:
for i in range(2,num1):
if (num1%i)==0:
print(num1,"is not a prime number")
print(i,'x',num1//i,'=',num1)
break
else:
print(num1,'is a prime number')
else:
print(num1,'is not a prime number')
'''
| true |
70d4ae0a45fc2dc7f3ce963f3d8c69d3e9834a2a | Akarthikeyan91/TestGit | /reverse.py | 1,224 | 4.125 | 4 | #!/c/Python36/python
###### String reverse with range ######
s = "Hello"
s1= ""
n = len(s) + 1
for i in range(-1,-n,-1):
s1 = s1 + s[i]
print(s1)
s = "Hello" ###### simplest way
print(''.join(s[i] for i in range(-1,-(len(s)+1),-1)))
print(''.join(reversed('a string'))) ###### sorted
###### String reverse with slice operation #######
s='python'
print(s[::-1])
###### String reverse with for loop ##########
def reverse(text):
s=''
for i in text:
s= i + s
return s
print(reverse('hai'))
###### String reverse with recursive method ##########
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
s = "Geeksforgeeks"
print("The original string is : ")
print(s)
print("The reversed string(using recursion) is : ")
print(reverse(s))
##################################################
# Python code to reverse a string
# using reversed()
# Function to reverse a string
def reverse(string):
string = "".join(reversed(string))
return string
s = "Geeksforgeeks"
print ("The original string is : ",)
print (s)
print ("The reversed string(using reversed) is : ")
print (reverse(s))
| false |
da062560647d69b8fac9d0686270087b1851023f | TjeerdH/Number-guess-game | /guess.py | 2,830 | 4.125 | 4 | import random
x = random.randrange(100)
while True:
count = 0
guess = input("Guess a number between 0 and 100 ")
try:
if x != int(guess):
if x % 2 == 0:
print("It is an even number!")
count += 1
break
else:
print("It is an odd number!")
count += 1
break
elif x == int(guess):
print("Lucky guess! But you are correct!")
exit()
except ValueError:
print("You don't know what a number is? Only submit numbers between 0 and 100!")
count += 1
continue
while True:
try:
guess = input("Try again! ")
if int(guess) != x:
if x < 50:
print("It is smaller then 50!")
count += 1
break
elif x > 50:
print("It is greater then 50!")
count += 1
break
elif x == int(guess):
print("You are correct! Not bad on second try!")
exit()
except ValueError:
print("Really? What about numbers don't you understand? Only submit numbers between 0 and 100!")
count += 1
continue
while True:
try:
guess = input("Try again! ")
if int(guess) != x:
if 0 < x < 25:
print("It is between 0 and 25!")
count += 1
break
elif 26 < x < 50:
print("It is between 26 and 50!")
count += 1
break
elif 51 < x < 75:
print("It is between 51 and 75!")
count += 1
break
elif 76 < x < 100:
print("It is between 76 and 100!")
count += 1
break
elif int(guess) == x:
count += 1
print(f"Well done in {count} tries! You are correct!")
exit()
except ValueError:
print("Come on, You should know how this works by now! Only submit numbers between 0 and 100!")
count += 1
continue
if guess != x:
while guess != x:
try:
guess = int(input("Try again! "))
except ValueError:
print("Hey dumdum, Only submit numbers between 0 and 100!")
count += 1
continue
if guess == x:
count += 1
print(f"You have guessed correctly! In {count} tries!")
exit()
elif guess < x:
print("The answer is higher!")
count += 1
continue
elif guess > x:
print("The answer is lower!")
count += 1
continue
elif guess == x:
count += 1
print(f"Well done in {count} tries!")
| true |
d8d759f9ee97a09a1d1d03d79e9c996ae287ebd9 | davidbUW/Intro-to-Python-Class | /hw3.py | 915 | 4.21875 | 4 | evenlist = "-"
evenlist = list(evenlist)
oddlist = "-"
oddlist = list(oddlist)
def number_program():
while True:
start = int(input("Enter a starting number: "))
end = int(input("Enter an ending number: "))
if start < 1:
print("ERROR: Starting number must be greater than 1")
elif end < 5*start:
print("ERROR: Ending number greater than 5 times starting number")
else:
for x in range(start,end+1,1):
evenlist.append(x)
del evenlist[0]
for index, number in enumerate(evenlist):
if number % 2 == 0:
print("{} [{}]".format(number, str(index)))
else:
oddlist.append(number)
del oddlist[0]
total = sum(oddlist)
print("The sum of odd numbers is",total)
break
number_program()
| true |
5decd85f916fceade200d88af89eb62385a59cf1 | DonyTawil/LPTHW | /ex.py/ex5.py | 631 | 4.15625 | 4 | dt_name='dony'
dt_height=163 #centimiters
dt_heights=dt_height/2.54 #to convert centimiters into inches for extra credit from tutorial.
dt_age=18
dt_weight=55
dt_weights=dt_weight*2.2 #extra cr. kilo into pounds
dt_eyes='brown'
dt_teeth='white'
dt_hair='dark brown'
print ('lets talk about %s.'%dt_name)
print ("he's %d inches tall"%dt_heights)
print ("he's %d pounds heavy"%dt_weights)
print ("and he's got %s eyes and %s hair."%(dt_eyes,dt_hair))
print ("he's teeth are usually %s depending on how well he's brushed"%dt_teeth)
print ("If I add %d with %d and %d, I get %d."%(dt_height, dt_weight, dt_age, dt_height+dt_weight))
| true |
8f988e4a800f92702f77f0df4f36ad84e84f108a | DonyTawil/LPTHW | /ex.py/ex12.py | 254 | 4.1875 | 4 | name=input('what is your name? ')
age=input("what is your age? ")
height=input('''how tall are you? ''')
weight=input('how much do you weigh? ')
print ("so %s ,you're %s years old ,%s centimiters tall, and you weigh %s kilos"%(name,age,height,weight))
| true |
475778c024e9a48bbf4d902ff3d8f76f78f5c975 | omakasekim/python_algorithm | /00_자료구조 구현/chaining용 연결리스트.py | 1,719 | 4.15625 | 4 | # 해시테이블에서 충돌이 일어날 경우를 위한 chaining 용 링크드리스트 구현
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def find_node_with_key(self, key):
iterator = self.head
while iterator is not None:
if iterator.key == key:
return iterator
iterator = iterator.next
return None
def append(self, key, value):
new_node = Node(key, value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
def delete(self, node_to_delete):
if self.head is self.tail:
self.head = None
self.tail = None
elif self.tail is node_to_delete:
self.tail = self.tail.prev
self.tail.next = None
elif self.head is node_to_delete:
self.head = self.head.next
self.head.prev = None
else:
node_to_delete.prev.next = node_to_delete.next
node_to_delete.next.prev = node_to_delete.prev
def __str__(self):
str = ''
iterator = self.head
while iterator is not None:
str += f'{iterator.key}: {iterator.value}\n'
iterator = iterator.next
return str
my_list = LinkedList()
my_list.append('지우', '0521')
my_list.append('지희', '0117')
my_list.append('광호', '0207')
print(my_list) | true |
d14be530e0781a8f77d4a450f4ef239dc633054f | ritesh3556/PythonConcepts | /dictionary_comprehension.py | 370 | 4.21875 | 4 | # dictionary comprehension------->
#square = {1:1,2:4,3:9}
square = {num:num**2 for num in range(1,11)}
print(square)
square = {f"square of {num} is ":num**2 for num in range(1,11)}
print(square)
for k,v in square.items():
print(f"{k} :{v}")
string = "harshit"
new_dictionary = {char:string.count(char) for char in string}
print(new_dictionary)
| false |
e32b155a9b4b06ed347ed5412658796f8435abd1 | Jayaprakash1998/Python-practice-problems-set-5 | /Prison Security Protocol.py | 2,171 | 4.21875 | 4 | ''' QUESTION:
Prison Security Protocol :
There is a highly secure prison that holds the most dangerous criminals in the world. On 2nd November 2019,
the prison officials received a warning that there was an attack planned on the prison to free the criminals.
So, the prison officials planned a quick evacuation plan. They planned to shift all the criminals in the prison to a different place.
A military level armored vehicle is waiting at the prison gate, they want to load all the prisoners inside the vehicle so they can be transferred to a secure location.
The prison has a certain number of cells and each cell has a certain number of people and no cells are empty.
As a safety method, the prison officials would like to group two cells together at one time, so prisoners from two cells will be moved to a dormitory.
Once you narrow the prisoners to two dormitories, you can then combine them to send them into the armored vehicle.
Shifting one prisoner from one cell to another will take one minute.
For example, let’s say there are three cells A, B and C. Prisoner from any of the two cells are moved to a dormitory,
let’s say we are combining cells A and B to form AB, now we are left with two blocks of prisoners, now we can add them to the vehicle,
so what will be the minimum time taken in total to load all the prisoners into the vehicle?
Input Format :
The first line of input has one integer input N, where N is the number of cells in the prison.
The second line of input has N spaced integers specifying the number of prisoners in each cell and no cell is empty.
Input Constraints : 2<=N<=10^9
1<=a[i]<=10^9
N - Number of cells
a[i] - prisoner count in i'th cell
Output Format : Minimum possible integer
Sample Input :
8
1 2 3 4 5 6 7 8
Sample Output :
119
HINTS:
1 - Sometimes it's better to have things in order.
2 - Sort in ascending order.
3 - Prefix sum.
'''
# ANSWER:
n = int(input())
l = list(map(int,input().split(' ')))
l.sort()
s = (n-1)*l[0]
for i in range(1,n):
s+= ((n-i)*l[i])
print(s)
| true |
205a7325dec447cab3994b95ab5ae41234425a93 | JustonSmith/Coding_Dojo | /python_stack/learn_assignments/functions_basics_I/functions_basic_I.py | 1,652 | 4.125 | 4 | # #1
# def number_of_food_groups():
# return 5
# print(number_of_food_groups())
# # The terminal will return 5.
# #2
# # There is an undefined variable so the function will not run.
# #3
# def number_of_books_on_hold():
# return 5
# return 10
# print(number_of_books_on_hold())
# # The terminal will return 5.
# #4
# def number_of_fingers():
# return 5
# print(10)
# print(number_of_fingers())
# # The terminal will again return 5.
# #5
# def number_of_great_lakes():
# print(5)
# x = number_of_great_lakes()
# print(x)
# # The terminal will return 5 and none.
# #6
# def add(b,c):
# print(b+c)
# print(add(1,2) + add(2,3))
# # The terminal will return 3 and 5
# #7
# def concatenate(b,c):
# return str(b)+str(c)
# print(concatenate(2,5))
# # The terminal will return 25.
# #8
# def number_of_oceans_or_fingers_or_continents():
# b = 100
# print(b)
# if b < 10:
# return 5
# elif:
# return 10
# return 7
# print(number_of_oceans_or_fingers_or_continents())
# # The terminal will return 10, 7.
# #9
# def number_of_days_in_a_week_silicon_or_triangle_sides(b,c):
# if b<c:
# return 7
# else:
# return 14
# return 3
# print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3))
# print(number_of_days_in_a_week_silicon_or_triangle_sides(5,3))
# print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3) + number_of_days_in_a_week_silicon_or_triangle_sides(5,3))
# # The terminal will print 7, 14, and 21.
# #10
# def addition(b,c):
# return b+c
# return 10
# print(addition(3,5))
# # The terminal will print 8.
| true |
c704e775f3c97c4582fb40dce0e5fdb93fa85108 | darkCavalier11/sort-python | /insertion_sort.py | 429 | 4.15625 | 4 | def insertion_sort(array, reverse=False):
if reverse:
array = [-1*e for e in array]
for j in range(1, len(array)):
key = array[j]
i = j - 1
while i > -1 and array[i] > key:
array[i+1] = array[i]
i -= 1
array[i+1] = key
if reverse:
array = [-1*e for e in array]
return array
print(insertion_sort([5,2,4,6,1,3], reverse=True))
| false |
6f5d6c116039b2f8b4ea1184e430a40460de9217 | LuisHenrique01/Questoes_Fabio | /fabio_04_31_while_numeros_romanos.py | 2,321 | 4.28125 | 4 | def main():
numero = int(input("Numero de até 3 digitos: "))
print('O numero em romano é: %s'%mil_romano(numero))
def mil_romano(numero):
numero_romano = (numero // 1000) * 'M'
numero_romano_final = numero_romano + novecentos_romano(numero % 1000)
return numero_romano_final
def novecentos_romano(numero):
numero_romano = (numero // 900) * 'CM'
numero_romano_final = numero_romano + quinhentos_romano(numero % 900)
return numero_romano_final
def quinhentos_romano(numero):
numero_romano = (numero // 500) * 'D'
numero_romano_final = numero_romano + quatrocentos_romano(numero % 500)
return numero_romano_final
def quatrocentos_romano(numero):
numero_romano = (numero // 400) * 'CD'
numero_romano_final = numero_romano + cem_romano(numero % 400)
return numero_romano_final
def cem_romano(numero):
numero_romano = (numero // 100) * 'C'
numero_romano_final = numero_romano + noventa_romano(numero % 100)
return numero_romano_final
def noventa_romano(numero):
numero_romano = (numero // 90) * 'XC'
numero_romano_final = numero_romano + ciquenta_romano(numero % 90)
return numero_romano_final
def ciquenta_romano(numero):
numero_romano = (numero // 50) * 'L'
numero_romano_final = numero_romano + quanrenta_romano(numero % 50)
return numero_romano_final
def quanrenta_romano(numero):
numero_romano = (numero // 40) * 'XL'
numero_romano_final = numero_romano + dez_romano(numero % 40)
return numero_romano_final
def dez_romano(numero):
numero_romano = (numero // 10) * 'X'
numero_romano_final = numero_romano + nove_romano(numero % 10)
return numero_romano_final
def nove_romano(numero):
numero_romano = (numero // 9) * 'IX'
numero_romano_final = numero_romano + cinco_romano(numero % 9)
return numero_romano_final
def cinco_romano(numero):
numero_romano = (numero // 5) * 'V'
numero_romano_final = numero_romano + quatro_romano(numero % 5)
return numero_romano_final
def quatro_romano(numero):
numero_romano = (numero // 4) * 'IV'
numero_romano_final = numero_romano + um_romano(numero % 4)
return numero_romano_final
def um_romano(numero):
numero_romano = (numero // 1) * 'I'
return numero_romano
if __name__ == '__main__':
main()
| false |
32ad867849b95f3aa479b09c73ae7abb4d033955 | 757u/CSE | /Hangman(Jazmin Ambriz).py | 1,589 | 4.34375 | 4 | import random
# This is a guide of how to make hangman
# 1. Make a word bank - 10 items (checked)
# 2. Select a random item to guess (checked)
# 3. take in a letter and add it to a list of letters_guessed (checked)
# -up to ten incorrect guesses (checked)
# guesses_left = 10 (checked)
# list of letters that you have guesses (checked)
# you only reveal the letter if its on a list of letters_guessed
# letters_guessed = ('e', 'h', "o', 's', "p',
# 4. Reveal Letters based on input
# 5. Create win and lost conditions
# turn random word into a list
# you will use the "".join(l1) to make it look pretty
word_bank = ["Afghanistan", "Bosnia and Herzegovina", "Central African Republic", "Djibouti", "Equatorial Guinea",
"Hungary", "Luxembourg", "Mozambique", "Switzerland", "Ukraine"]
word = random.choice(word_bank).lower()
print(word)
# guess = 10
guess_left = 10
list_of_letters_guessed_by_player = [' ']
player_letter = ""
while guess_left > 1:
output = []
for letter in word:
if letter in list_of_letters_guessed_by_player:
output.append(letter)
else:
output.append("*")
output = ''.join(output)
print(output)
if player_letter not in word:
guess_left -= 1
print("you have %s guesses left" % guess_left)
if "*" not in output:
print("You Win")
exit(0)
player_letter = input("What is your letter guess?").lower()
list_of_letters_guessed_by_player.append(player_letter)
print(list_of_letters_guessed_by_player)
print(" You Lost")
print("The word was:")
print(word)
| true |
7b4f8e15418b7571c7d126127cbb8779f2924238 | hmanoj59/python_scripts | /circle_linkedlist.py | 785 | 4.28125 | 4 | def circle_node(node):
marker1 = node
marker2 = node
while marker2 != None and marker2.nextnode != None:
marker1 = marker1.nextnode
marker2 = marker2.nextnode.nextnode
if marker1 == marker2:
return True
return False
#Initializing node
class Node(object):
def __init__(self,node):
self.value = value
self.nextnode = None
'''
Given a singly linked list, write a function which takes in the first node in a singly linked list and returns a boolean
indicating if the linked list contains a "cycle". A cycle is when a node's next point actually points back to a previous node
in the list. This is also sometimes known as a circularly linked list. You've been given the Linked List Node class code:
'''
| true |
3c8a9c05f9caf0bc70b7f52762fb64198f0994be | Sharks33/HackerRankSolutions | /Python/staircase.py | 822 | 4.65625 | 5 | '''
Consider a staircase of size n = 4:
#
##
###
####
Observe that its base and height are both equal to n, and the image is drawn
using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n.
INPUT FORMAT
A single integer, n, denoting the size of the staircase.
OUTPUT FORMAT
Print a staircase of size n using # symbols and spaces.
Note: The last line must have 0 spaces in it.
SAMPLE INPUT
6
SAMPLE OUTPUT
#
##
###
####
#####
######
EXPLANATION
The staircase is right-aligned, composed of # symbols and spaces, and has a
height and width of n = 6.
'''
#!/bin/python
import sys
n = int(raw_input().strip())
space = ''
pound = ''
for i in xrange(n):
n = n - 1
space = ' ' * n
pound += '#'
print space + pound
| true |
46ec164997037a09d38150b738cf81aab1b75f31 | JacksonMike/python_exercise | /python练习/老王开枪/Demo11.py | 772 | 4.21875 | 4 | class Cat:
#初始化对象
def __init__(self,newName,newAge):
self.name = newName
self.age = newAge
def __str__(self):
return "%s的年龄是:%d"%(self.name,self.age)
def introduce(self):
print("%s的年龄是:%d"%(self.name,self.age))
T = Cat("Tom",12)
print(T)
class Animal:
def __init__(self,newA,newB):
self.A = newA
self.B = newB
def __str__(self):
return "%s的年龄是:%d"%(self.A,self.B)
#魔方方法,打印return返回的数据
C = Animal("Jack",12)
print(C)
class Bird:
def __init__(self,newName):
self.name = newName
def printName(self):
print("名字为:%s"%self.name)
def myPrint(Bird):
Bird.printName()
dog1 = Bird("Kity")
myPrint(dog1)
| false |
9b6eb3dfa5fef600879b57f509abef3f6f6b6ccc | davidgower1/Python | /Ex3.py | 968 | 4.5 | 4 | #This line prints a statement about counting my chickens
print("I will now count my chickens:")
# These lines count the chickens, Hens and Roosters
print("Hens", float(26) + float(30) / float(6))
print("Roosters", float(100)-float(25) * float(3) % float(4))
# Here I am makeing the statement about counting the eggs
print("Now I will count the eggs:")
#Here I count the eggs
print(3 + 2 + 1 - 5 + 4 % -1 / 4 + 6)
# This line asks about comparing numbers
print("Is it true that 3 + 2 < 5 - 7?")
#This line compares the numbers
print( 3 + 2 < 5 - 7)
#These lines evaluates each part of the equation in line 13
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
#This line makes the statement
print("Oh, that's why it's False.")
#This line asks if you want to see more
print("How about some more.")
#These lines evaluate the comparison
print(" Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
#Finished
| true |
1019f29bd5a5f767ece688fbef960be1ab4625da | Prakhar-Saxena/ProjectEulerSolutions | /quickSort | 290 | 4.28125 | 4 | #!/usr/bin/env python3
#This is an amazing way to write the quick sort method.
def quickSort(arr):
if len(arr) <= 1:
return arr
else:
return quickSort( [x for x in arr[1:] if x < arr[0]]) + [arr[0]]+quickSort([x for x in arr[1:] if x>=arr[0]])
print quickSort([3,1,4,1,5,9,2,6,5])
| true |
cdf04a7b1ff723776c2433516bc0eb0490344835 | sidneykung/python_practice | /01_easy/checking_x.py | 555 | 4.25 | 4 | # 1. is_even
# Define a function is_even that will take a number x as input.
# If x is even, then return True.
# Otherwise, return False
def is_even(x):
if x%2 == 0:
return True
else:
return False
print is_even(5) # False
print is_even(6) # True
# 2. is_int
# Define a function is_int that takes a number x as an input.
# Have it return True if the number is an integer and False otherwise.
def is_int(x):
if x%1 == 0:
return True
else:
return False
is_int(7.0) # True
is_int(7.5) # False
is_int(-1) # True | true |
49067afca8940e388ff099ed58b68726868d22e8 | thekingmass/OldPythonPrograms | /timedateModule.py | 287 | 4.21875 | 4 | from datetime import datetime
from datetime import date
'''
datetime function for time and time function for date
'''
time = datetime.now()
print(time)
print(date.today())
print(date.today().weekday()) # this will give the week date for today as it counts monday as 0 and saturday as 6
| true |
3e0173ac2ea4d30aafdbc6851636cb3a96f922e7 | supriyo-pal/Joy-Of-Computing-Using-Python-All-programms | /binary search by recursion.py | 1,226 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 21:03:53 2020
@author: Supriyo
binary search always takes sorted list as input
"""
#start=0 and end=last
def binary_search(l,x,start,end): #l is the list and x is the searching elelment
#base case: 1 element is in the list , start==end
if start == end:
if l[start]==x:
return start
else:
return -1
#more than one element present in the list
else:
mid=int((start+end)/2) #else use (start+end)//2
if l[mid]==x: #if the middle is the searched element then return mid
return mid
elif l[mid]>x:
#left half
return binary_search(l,x,start,mid-1)
#because element is not present in the right half so discard the right half
else:
#right half
return binary_search(l,x,mid+1,end)#checking after the mid point
l=[i for i in range(1,11)]
x=int(input("enter the element to be searched between 1 to 10 :"))
index=binary_search(l,x,0,len(l)-1)
#print("Element ",x,"is present at:",index)
if index==-1:
print("element is not found")
else:
print(x,' is found at ',index+1) | true |
cc472c44fff5813680b7019dda413e81df991634 | abhishekbajpai/python | /even-odd.py | 301 | 4.40625 | 4 | # Ask the user for a number.
# Depending on whether the number is even or odd,
# print out an appropriate message to the user.
numb = int(input("Please enter a number to check if even or odd: "))
if numb%2 == 0:
print("Entered number is even. ")
else:
print("You have enetered odd number") | true |
d78a468f240b5a01b8da3bf5b05abefe449f99e0 | ryanlntn/mitx.6.00.1x | /l3.problem9.py | 714 | 4.15625 | 4 | # L3 Problem 9
low = 0
high = 100
guess = (low + high) / 2
print "Please think of a number between " + str(low) + " and " + str(high) + "!"
while True:
print("Is your secret number " + str(guess) + "?")
print "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.",
answer = raw_input("Enter 'c' to indicate I guessed correctly. ")
if answer == 'h':
high = guess
guess = (low + high) / 2
elif answer == 'l':
low = guess
guess = (low + high) / 2
elif answer == 'c':
print("Game over. Your secret number was: " + str(guess))
break
else:
print("Invalid Answer! Please enter 'h', 'l', or 'c'.")
| true |
c0f2b4cc267623aacdb13b188350ada0efc44311 | vipingujjar1/python-edsystango | /homework/29 July 2019/greaterDigit.py | 270 | 4.15625 | 4 | # find greater digit from three digit no.
num1=int(input("Enter a three digit no. :"))
for i in range(3):
if i==0:
max=num1%10
num1=num1//10
else:
temp=num1%10
if temp>max:
max=temp
num1=num1//10
print(max)
| true |
27e9c6ae86496fd733f0f1aa7181af06afdd1e82 | nspofford1/tech-savvy | /Assignment3.py | 1,246 | 4.125 | 4 | #Excercise5
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
#lowercase1 is seeing if the first letter is lowercase, if it is, it returns True and does not check any other letter
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
#lowercase2 is the same as the first function; however it adds unnecessary strings to booleans and to the c
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
#lowercase3 only sees if the last letter is lowercase or not
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
#lowercase4 is checking every letter; however it is true if there is even one lowercase letter
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
#lowercase5 is checking every letter and correctly returns if all the letters are lowercase
#Excerise6
def rotate_word(string,integer):
result = ''
for i in string:
i = chr(ord(i) + integer)
result = result + i
return (result)
print (rotate_word("cheer",7)) | true |
ff3b61e30c9f266ca478636bb0c7c15631bbe402 | kristuben/PythonFolder | /drawshapes.py | 622 | 4.3125 | 4 | from turtle import *
import math
#Name your turtle
ke=Turtle()
colormode(255)
#Set Up your screen and starting position.
setup(500,300)
ke.setposition(0,0)
### Write you code below:
color=input('Enter the color of the shapes:')
ke.pendown()
ke.pencolor(color)
length = input('Enter the length of the shapes:')
for number in range (4):
ke.forward(int(length))
ke.right(90)
for number in range (3):
ke.forward(int(length))
ke.left(120)
sides= input('Enter the number of sides for the shape:')
for number in range (int(sides)):
ke.forward(int(length))
ke.left(int(360/int(sides)))
exitonclick()
| true |
6d055d9ec5c902b107c942d9d8b6a2550e59b964 | annkon22/chapter4 | /ex7.py | 765 | 4.34375 | 4 | #Using the turtle graphics module, write a recursive
#program to display a Hilbert curve
###############################################
########## HILBERT CURVE ###########
import turtle
size = 10
def main():
t = turtle.Turtle()
my_wd = turtle.Screen()
hilbert(t, 5, 90)
my_wd.exitonclick()
def hilbert(t, level, angle):
if level == 0:
return
t.color('Blue')
t.width(5)
t.speed(2)
t.right(angle)
hilbert(t, level - 1, - angle)
t.forward(size)
t.left(angle)
hilbert(t, level - 1, angle)
t.forward(size)
hilbert(t, level - 1, angle)
t.left(angle)
t.forward(size)
hilbert(t, level - 1, - angle)
t.right(angle)
main()
| false |
cd9faf9eac1d1fa9932a9e577708ece3f085a976 | annkon22/chapter4 | /ex12.py | 1,832 | 4.46875 | 4 | #Modify the Tower of Hanoi program using turtle graphics to animate the movement of the disks.
#Hint: You can make multiple turtles and have them shaped like rectangles.
import turtle as t
def move_tower(height, from_pole, to_pole, with_pole):
if height >=1:
move_tower(height - 1, from_pole, with_pole, to_pole)
move_disk(from_pole, to_pole)
move_tower(height - 1, with_pole, to_pole, from_pole)
def move_disk(fp, tp):
print("moving disk from ", fp, "to", tp)
def move_turtle(turt, position):
print("The", turt, "goes to", position)
def bigger(turt1, turt2):
return turt1.shapesize() > turt2.shapesize()
def moved(height,pole):
if height[pole] == 3:
return True
def main():
my_win = t.Screen()
big = t.Turtle()
big.shape('square')
big.shapesize(50)
mid = t.Turtle()
mid.shape('square')
mid.shapesize(30)
small = t.Turtle()
small.shape('square')
small.shapesize(15)
list_turts = [big, mid, small]
my_win.exitonclick()
poleA = []
poleB = []
poleC = []
poles = [poleA, poleB, poleC]
while not moved:
if len(poleA) == 3 and len(poleB) == 0:
move_disk(poleA, poleB)
len(poleA) -= 1
len(poleB) += 1
move_turtle(list_turts[2], pos21)
list_turts[2].goto(pos21)
if len(poleA) == 2 and len(poleC) == 1:
if poleA[2] not bigger poleC:
move_turtle(poleA[2], pos32)
#######positions
pos11 = [0, 0]
pos12 = [0, 50]
pos13 = [0, 90]
pos21 = [40, 0]
pos22 = [40, 50]
pos23 = [40, 90]
pos31 = [80, 0]
pos32 = [80, 50]
pos33 = [80, 90]
################
move_tower(3, "A", "B", "C")
main()
| true |
0045217a7a04f74694ad26615f502be10bcff7db | MMVonnSeek/Hacktoberfest2021_beginner | /Python3-Learn/list_manipulation_DFRICHARD.py | 1,121 | 4.34375 | 4 | // AUTHOR: Richard
// Python3 Concept: Manipulating data in lists
// GITHUB: https://github.com/DFRICHARD
//Add your python3 concept below
domestic_animals = [] #creating an empty list to contain domestic animals
domestic_animals.append("dog") #adding dog to the list domestic_animals
print(domestic_animals) # The result: ["dog"]
domestic_animals.append("cat")
print(domestic_animals) #The result: ["dog", "cat"]
wild_animals = ["lion", "elephant", "tiger" , "leopard"]
animals = domestic_animals + wild_animals #Joining lists
print(animals) #The result : ["dog", "cat", "lion", "elephant", "tiger", "leopard"]
print(animals[0]) #printing the first item of the list of animals : dog
print(animals[2:5]) #printing the third to fifth item of the list of animals
print(len(animals)) #printing the number of items in the list of animals
animals[3] = "pen" #replacing the fourth item(elephant) with "pen"
print(animals) # the result: ["dog", "cat", "lion", "pen", "tiger", "leopard"]
animals.remove("pen") #removing pen from the list of animals
print(animals) # the result: ["dog", "cat", "lion", "tiger", "leopard"]
| true |
21b8e68f4d4820cb47c3ed171c6d287819c33018 | MMVonnSeek/Hacktoberfest2021_beginner | /Python3-Learn/SortAlphabeticalOrder_erarijit.py | 305 | 4.5625 | 5 | # Program to sort alphabetically the words form a string provided by the user
# take input from the user
my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
| true |
fbc976c9592476b372056343a82fa714b065fcac | MMVonnSeek/Hacktoberfest2021_beginner | /Python3-Learn/Palindrome_Shyam-2001.py | 375 | 4.1875 | 4 | // AUTHOR: Devendra Patel
//Python3 Concept: Palindrome
// GITHUB: https://github.com/github-dev21
print("Enter the Number ")
num = int(input())
temp = num
reverse = 0
while(num>0):
dig = num%10
reverse = reverse*10+dig
num = num//10
print(reverse)
if temp==reverse:
print("Number is in Palindrome")
else:
print("Number is not in Palindrome") | true |
2a2d5262d2828aa4649aaa8bd6b6ff66ea24891c | MMVonnSeek/Hacktoberfest2021_beginner | /Python3-Learn/magic_number-sumitbro.py | 939 | 4.1875 | 4 | # Python3-Learn
// AUTHOR: Sumit Sah
// Python3 Concept: Check Magic number
// GITHUB: https://github.com/sumitbro
# Magic number concept
#A magic number is that number whose repeated sum of its digits till we get a single digit is equal to 1.
# Example:
# original number= 1729
# sum of digits= 1+7+2+9=19
# 1+9=10
# 1+0=1
# 1729 is magic number
#code
import math
num = int(input("Enter a Number \n"))
digitCount = int(math.log10(num))+1
sumOfDigits = 0
temp = num #copying num
#calculating sum of digits of temp(i.e num) until
#sumOfDigits is a single digit
while( digitCount > 1):
sumOfDigits = 0
while(temp > 0):
sumOfDigits += temp%10
temp = temp//10
temp = sumOfDigits
#count the digits of sumOfDigits
digitCount = int(math.log10(sumOfDigits))+1
#check whether sumOfDigits == 1
if(sumOfDigits == 1):
print("Magic number")
else:
print("Not a magic number") | true |
1348b71b806efdd6f0201339b28e51d52cc133ef | OcaeanYan/Python-Basics | /高级特性/5.迭代器.py | 1,058 | 4.125 | 4 |
if __name__ == '__main__':
# 可以使用isinstance()判断一个对象是否是Iterable对象:
# from collections.abc import Iterable
# print(isinstance([], Iterable))
# print(isinstance({}, Iterable))
# print(isinstance('abc', Iterable))
# print(isinstance((x for x in range(10)), Iterable))
# print(isinstance(100, Iterable))
# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
# 可以使用isinstance()判断一个对象是否是Iterator对象
from collections.abc import Iterator
print(isinstance((x for x in range(10)), Iterator))
print(isinstance({}, Iterator))
print(isinstance([], Iterator))
print(isinstance('abc', Iterator))
# 把list、dict、str等Iterable变成Iterator可以使用iter()函数:
print(isinstance(iter([]),Iterator))
print(isinstance(iter('abc'),Iterator))
# 凡是可作用于for循环的对象都是Iterable类型;
# 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列; | false |
230d895ba0af79ebb5d8215a2ff435d9c44a02bc | rajatrj16/PythonCode | /PythonCode/Function_MilesToKilometer.py | 211 | 4.1875 | 4 | miles = float(input('Enter Miles: '))
print('Miles: ')
print(miles)
print(' ')
def convert(miles):
print('Converting Miles to Kilometer: ')
return 1.60934 * miles
km = convert(miles)
print(km)
| false |
ea434795e0deee584fff9e426d35cfce5ef36024 | rajatrj16/PythonCode | /PythonCode/AddNumber.py | 248 | 4.1875 | 4 | value=1
summ=0
print("Enter Numbers to add to the sum")
print("Enter 0 to quit.")
while value !=0:
print("Current Sum: ",summ)
value=int(input("Enter Number? "))
summ+=value
print("---")
print("Total Sum is: ",summ)
| true |
59d1c057abf78be9d606f4aaf7d96d811210834c | AC740/Py | /python37/priorityQueue.py | 691 | 4.28125 | 4 | customers = []
customers.append((2, "Harry")) #no sort needed here because 1 item.
customers.append((3, "Charles"))
customers.sort(reverse=True)
#Need to sort to maintain order
customers.append((1, "Riya"))
customers.sort(reverse=True)
#Need to sort to maintain order
customers.append((4, "Stacy"))
customers.sort(reverse=True)
while customers:
print(customers.pop(0))
print(customers)
#Will print names in the order: Stacy, Charles, Harry, Riya.
test = []
test.append('a')
test.append('b')
test.append('c')
test.append('d')
print(test)
# test.insert('1')
# test.insert('2')
# test.insert('3')
# test.insert('4')
test.remove('a')
print(test) | true |
0c5de4f5507edac29ad3840714173cfdaf61ac47 | sahasatvik/assignments | /CS2201/problemset01/problem01.py | 389 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Input your IISER email in format name-rollno@iiserkol.ac.in, extract the name,
roll no using split() and print them.
"""
email = input("Enter your email in the format name-rollno@iiserkol.ac.in : ")
try:
name_roll, domain = email.split("@")
name, rollno = name_roll.split("-")
print(f"Your name is {name}, your roll number is {rollno}.")
except ValueError:
print("Invalid format!")
| true |
dbb34903bf5365ba09f52c12de86f32d94c37ff0 | Algorant/leetcode | /07_reverse_integer.py | 519 | 4.34375 | 4 | '''
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
'''
def reverse(x):
#check if negative
neg_check = 1
# ignoring negative sign, convert to str
if x < 0:
neg_check = -1
x_str = str(x)[1:]
# if positive, convert to str
else:
x_str = str(x)
# reverse the str
x = int(x_str[::-1])
return 0 if x > pow(2, 31) else x * neg_check
| true |
b5ec7405a7c8b68560146a9fa9565063defaa165 | Kitrinos/Ch.05_Looping | /5.1_Coin_Toss.py | 778 | 4.3125 | 4 | '''
COIN TOSS PROGRAM
-----------------
1.) Create a program that will print a random 0 or 1.
2.) Instead of 0 or 1, print heads or tails. Do this using if statements. Don't select from a list.
3.) Add a loop so that the program does this 50 times.
4.) Create a running total for the number of heads and the number of tails and print the total at the end.
'''
import random
head = 0
tails = 0
for i in range (0,51):
x = random.randrange(0,2)
print(x)
if x== 1:
tails+=1
print("Your got a tail")
else:
head+=1
print("You got a head")
print("You got this many heads : ",head)
print("You got this many tails : ", tails)
for i in range (0,50):
i = random.randrange(0,51)
print(i)
# if i%2 == 1:
# tails+= 1
# else :
# head+= 1
| true |
6e2b7809c92d27cadc9618ed4ccee34432ab6f02 | jmsaavedra/Interactive-Prototyping-S15 | /python/inclass.py | 268 | 4.3125 | 4 |
x = raw_input("Please enter an integer: ")
x = int(x)
if x < 0:
x = 0
print 'no negative numbers allowed!'
elif x == 2:
print 'x is 2!!'
elif x > 10:
print 'x is greater than 10!'
else:
print 'x is less than 10, greater 0 and NOT 2'
print 'done! exiting now.'
| true |
7463dd78101526c91de711352501cf2b0a465c15 | honestobx/exercicios_em_python | /3_notas_media.py | 349 | 4.1875 | 4 | # Faça um programa que leia as 3 notas de um aluno e calcule a média aritmética deste aluno.
nota1 = float(input("Entre com a primeira nota: "))
nota2 = float(input("Entre com a segunda nota: "))
nota3 = float(input("Entre com a terceira nota: "))
media = (nota1 + nota2 + nota3) / 3
print("A média do aluno foi {:.1f}".format(media)) | false |
e5862c30d80f3886aa2a6ee34c200e40d0276259 | ankitchoudhary49/Daily-Assignments | /Assignment-9.py | 1,739 | 4.21875 | 4 | #Assignment 9
'''
Question 1:Name and handle the exception occured in the following program:
a=3
if a<4:
a=a/(a-3)
print(a)
'''
#Exception: ZeroDivisionError
a=3
if a<4:
try:
a=a/(a-3)
except:
a=int(input("please enter a value other than 3. "))
a=a/(a-3)
print(a)
'''
Question 2: Name and handle the exception occurred in the following program:
l=[1,2,3]
print(l[3])
'''
#Exception: IndexError
l=[1,2,3]
try:
print(l[3])
except:
l1=int(input("Enter an index smaller than 3. "))
if l1<3:
print(l[l1])
'''
Question 3: What will be the output of the following code:
# Program to depict Raising Exception
try:
raise NameError("Hi there") # Raise Error
except NameError:
print("An exception")
raise # To determine whether the exception was raised or not
'''
#The above code will print a NameError.
#Question 4: What will be the output of the following code:
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print("a/b result in 0")
else:
print(c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
'''
output: -5.0
a/b result in 0
'''
'''
#Question 5: Write a program to show and handle following exceptions:
1. Import Error
2. Value Error
3. Index Error
'''
try:
print(sys.version)
except:
print("Import Error")
try:
z=int(input("Enter any value other than int to see if it produces an error or not. "))
except ValueError:
z=int(input("Now enter an integer value. "))
print(z)
l=[1,2,3,4,5]
try:
print(l[8])
except IndexError:
y=int(input("Enter an index less than 4. "))
if(y<5):
print(l[y])
| true |
d9f193db5866194f1f3a2a3917a6a1317de589c6 | ankitchoudhary49/Daily-Assignments | /assignment-4.py | 1,307 | 4.3125 | 4 | #Asignment 4
#Question 1: Reverse the List.
print("*"*50)
list1=[1,2,3,4,5]
print(list1[::-1]) #list1.reverse() was not working so i had to use slice operator.
print("*"*50)
#Question 2: Extract all the uppercase letters from a string.
str1='My name is ANKIT CHOUDHARY.'
for i in str1:
if i.isupper()==True:
print(i,end=' ')
print("\n")
print("*"*50)
#Question 3: Split and Store the Values After TypeCasting.
str2=input("Enter a string:\n")
str3=str2.split(',')
print(str3)
lst=[]
for i in str3:
l=int(i)
lst.append(l)
print(lst)
print("*"*50)
#Question 4: Check for Palindrome.
str4=input("Enter a string:\n")
if str4==str4[::-1]:
print("String is a palindrome.")
else:
print("String is not palindrome.")
print("*"*50)
#Question 5: Understand Deep and Shallow Copy.
import copy as c
lst1=[1,2,[3,4],5]
lst2=c.deepcopy(lst1)
print(lst2)
print("*"*50)
'''
Difference between shallow and deep copy:
Shallow copy - if original object contains any reference to mutable objects, then the duplicate preferance variables will be created
pointing to old containing object but no duplicate objects gets created.
Deep copy - A deep copy constructs a new compound object and then, recursively inserts copies into it of the objects found in the original.
'''
| true |
db4dee6c383d948fc86d7c9aee1908214f79d58f | loc-dev/CursoEmVideo-Python-Part2 | /Fase12/Desafios/Desafio_037.py | 712 | 4.15625 | 4 | # Fase 12 - Condições Aninhadas
# Desafio 37
# Escreva um programa que leia um número inteiro qualquer
# e peça para o usuário escolher qual será a base de conversão:
# 1 para binário
# 2 para octal
# 3 para hexadecimal
num = int(input('Digite um número inteiro: '))
print('')
print('Escolha uma conversão: \nBinário [1] \nOctal [2] \nHexadecimal [3]')
op = int(input('Digite a opção desejada: '))
print('')
if op == 1:
print('Binário: ', bin(num).replace('0b', ''))
print('')
elif op == 2:
print('Octal: ', oct(num).replace('0o', ''))
print('')
elif op == 3:
print('Hexadecimal: ', hex(num).replace('0x', ''))
print('')
else:
print('Saindo do programa...')
| false |
dbf4133ce1e2db8d06175daf9f5daf9f837da365 | fernandobd42/Introduction_Python | /07_function.py | 2,055 | 4.71875 | 5 | '''
Funções, basicamente são subprogramas, dentro de um programa maior, utilizados para realizar uma tarefa específica.
'''
def say_hello(): #def define uma função, say_hello foi o nome que eu dei
return "Hello World" #return define o retorno desta função
#OBS:a identação(espaçamento) define o bloco que faz parte função
print(say_hello()) #print(mostra) a função definida acima
'''
Resultado:
Hello World
'''
#Acima mostramos uma função bastante simples, que retorna uma string.
#Agora vamos criar uma função um pouco mais complexa;
def numbers_with_limit(limit): #definindo a função numbers_with_limit que receberá o parâmetro limit
list = range(0,5) # definindo uma lista com intervalo entre 0 e 5
for number in list[0:limit]: #percorrendo a lista numero por numero do intervalor 0 até o limit
#o limit será passado na hora da invocação da função.
print(number) #printando(mostrando) os numeros que estão entre o intervalor de 0 até limit.
numbers_with_limit(3) #invocando a função atribuindo o numero 3 ao limit
'''
Resultado:
0
1
2
'''
print()
#outra maneira de criar uma mesma função seria,
def numbers_with_limit2(limit): #definindo a função numbers_with_limit2 que receberá o parâmetro limit
for number in range(limit): #percorrendo a lista numero por numero, até alcançar o limit
#o qual será passado na hora da invocação da função.'''
print(number) #printando(mostrando) os numeros que estão entre o intervalor de 0 até limit.
numbers_with_limit2(12) #invocando a função atribuindo o numero 12 ao limit
'''
Resultado:
0
1
2
3
4
5
6
7
8
9
10
11
'''
print()
#Criando uma função para explicar a recursividade(a função invoca ela mesmo dentro de si)
def fac(n): #fac recebe o parâmetro n
if n == 0: #se o valor de n for igual a 0
return 1 #retorna o resultado
else: #senão
return n * fac(n-1) #retorna o valor de n vezes a própria função, porém com o parâmetro modificado para decrementar em 1
print(fac(5)) #resultado: 120
| false |
022081786817ba3b960d45b0f1125692cff1a3bb | mcbishop/calculator_2 | /arithmetic.py | 1,516 | 4.15625 | 4 | import math
# def add(num1,num2,*therestnums):
# new_num = 0
# for i in therestnums:
# i = int(i)
# new_num = (int(new_num) + i)
# return (int(num1)+int(num2)+int(new_num))
#next task: change functions to use reduce().
# we will want to convert both arguments into a list along with therestnums if it exists.
# the final function will look something like: reduce(lambda x,y: x-y, therestnums)
def add(*therestnums):
print type(therestnums[0])
print therestnums
print therestnums[0]
intlist = [int(x) for x in therestnums[0]]
return (reduce(lambda x, y: x+y, intlist))
# new_num = 0
# for i in therestnums:
# i = int(i)
# new_num = (int(new_num) + i)
# return (int(num1)+int(num2)+int(new_num))
def subtract(num1, num2):
return int(num1) - int(num2)
def multiply(num1, num2):
return int(num1) * int(num2)
def divide(num1, num2):
# Need to turn at least argument to float for division to
# not be integer division
return float(num1) / float(num2)
def square(num1):
# Needs only one argument
return int(num1) * int(num1)
def cube(num1):
# Needs only one argument
return int(num1) * int(num1) * int(num1)
def power(num1, num2):
#return int(num1) ** int(num2) # ** = exponent operator
if (num1 < 0 and type(num2) == float):
return ValueError
num1 = float(num1)
num2 = float(num2)
return math.pow(num1,num2)
def mod(num1, num2):
return int(num1) % int(num2)
| true |
a16201f040fee1cee135952b9c1de1fc28c013b4 | mag389/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 528 | 4.25 | 4 | #!/usr/bin/python3
"""square with attribute file"""
class Square:
"""
Square - the square class
Currently blank class
__init__ - makes instance
"""
def __init__(self, _Square_size=0):
"""
creates square instance
_Square_size: self explanatory
"""
if type(_Square_size) is not int:
raise(TypeError("size must be an integer"))
if _Square_size < 0:
raise(ValueError("size must be >= 0"))
self._Square__size = _Square_size
| true |
8f04b4b1214f2eb4ab3fdb6fe62d5d18ec264aff | joeywangzr/File_Sorter | /file_sorter.py | 1,473 | 4.28125 | 4 | # Import necessary directories
import os, shutil
# Change working directory to user choice
dir = input('Please input the name of the directory you would like to sort: ')
os.chdir(dir)
print('Sorting files...')
# Check number of files in the directory
num_files = len([f for f in os.listdir('.') if os.path.isfile(f)])
# Continues sorting files until no more files are in the directory
while num_files > 0:
# Loops through all files in the working directory
for file in os.listdir(dir):
# Checks if "file" is a file
# Confirmed that "file" is a file
if '.' in file:
file = file[::-1]
# Isolates file type
fileType = file[0:file.index('.')]
fileType = fileType[::-1]
file = file[::-1]
# Creates a new folder for that file type
try:
os.mkdir(dir + '\\' + fileType)
# Move file into corresponding folder
shutil.move(dir + '\\' + file, dir + '\\' + fileType)
# If folder for that file type exists, do not create new folder; move to existing folder
except FileExistsError:
shutil.move(dir + '\\' + file, dir + '\\' + fileType)
# "file" is not a file
else:
# If files are left in the directory, the code continues to run
if num_files > 0:
continue
# If no more files are remaining, the code stops running
elif num_files == 0:
break
break
print('All files have been sorted!') | true |
02892e3a0ccc9faa07184ba3599a036804c65402 | theskinnycoder/python_crash_course | /7_DataStructures/5_MemberShipOperators.py | 1,077 | 4.53125 | 5 | # NOTE: MEMEBRSHIP OPERATORS : in, not in
# - In Strings :
my_string = 'She sells sea shells in the sea shore'
if 'sea' in my_string:
print('Present')
else:
print('Not present')
# - In Lists :
my_list = [1, 3 + 4j, 3.4, 'Rahul']
if 1 in my_list:
print('Present')
else:
print('Not present')
# - In Tuples :
my_tuple = (1, 3 + 4j, 3.4, 'Hero')
if 'Hero' not in my_tuple:
print('Not present')
else:
print('Present')
# - In Sets :
my_set = {43, 2.2, 3, 43}
if 43 in my_set:
print('Present')
else:
print('Not present')
# - In Dictionaries :
my_dict = {
1: 'C++',
2: 'Python',
3: 'Java',
}
# By default, keys are used to check. We can use keys() method for that too.
if 'Java' in my_dict:
print('Present')
else:
print('Not present')
# We can check in values, using values() method :
if 'Java' not in my_dict.values():
print('Present')
else:
print('Not present')
# We can also check pairs, using entries() method : Use tuples
if (3, 'Java') in my_dict.items():
print('Present')
else:
print('Not present')
| true |
092784978eccd9e9483ec1d318631c590253c53f | geog3050/matchison | /Quizzes/matchison_G5055_Quiz1.py | 583 | 4.125 | 4 | climate = input("Please input the climate (in lowercase) and then press enter: ")
temp_string = input("Please input all temperature measurements for this climate as a list enclosed in brackets (i.e. [24.7, 44, 76]): ")
temp_float = eval(temp_string)
print("climate: ", climate)
print("temperatures: ", temp_float)
if climate == "tropical":
for i in temp_float:
if i <= 30:
print("F")
else: print("U")
elif climate == "continental":
for i in temp_float:
if i <= 25:
print("F")
else: print("U")
else:
for i in temp_float:
if i<= 18:
print("F")
else: print("U")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.