blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6ff4fb20a4cb3fed80eab57bd874d5f8a3b6d934 | hstabelin/Python_Lista_Exercicios | /Lista3 - Repeticao/Exercicio10.py | 400 | 4.125 | 4 | # Faça um programa que receba dois números inteiros e gere os números
# inteiros que estão no intervalo compreendido por eles
a = int(input('Informe o primeiro valor: '))
b = int(input('Informe o segundo valor: '))
c = [0]
if a < b:
while a < b:
print(a)
c.append(a)
a = a + 1
exit()
else:
while a > b:
print(b)
c.append(b)
b = b + 1
| false |
419a64996f9270f2e25b6969d1352def3c969b76 | theboyarintsev/Python | /Part 3/Task 2.py | 832 | 4.28125 | 4 | # Напишите функцию, вычисляющую длину отрезка по координатам его концов.
# С помощью этой функции напишите программу, вычисляющую периметр треугольника по координатам трех его вершин.
# На вход программе подается 3 пары целых чисел — координат x₁, y₁, x₂, y₂, x₃, y₃ вершин треугольника.
from math import sqrt
print('x1, y1')
x1, y1 = map(float,input().split())
print('x2, y2')
x2, y2 = map(float,input().split())
print('x3, y3')
x3, y3 = map(float,input().split())
a = sqrt((x2-x1)**2+(y2-y1)**2)
b = sqrt((x3-x2)**2+(y3-y2)**2)
c = sqrt((x1-x3)**2+(y1-y3)**2)
p = (a+b+c)/2.0
print("%.04f"%(a+b+c)) | false |
1947fecfb584b3fcc6e8b795ee833d9f16fa1918 | niranjanh/RegExp | /regexp_16.py | 697 | 4.46875 | 4 | /*
Comprehension: Escape Sequence
Description
Write a regular expression that returns True when passed a multiplication equation. For any other equation, it should return False. In other words, it should return True if there an asterisk - ‘*’ - present in the equation.
Sample positive cases (should match all of these):
3a*4b
3*2
4*5*6=120
Sample negative cases (shouldn't match either of these):
5+3=8
3%2=1
Execution Time Limit
10 seconds
*/
import re
import ast, sys
string = sys.stdin.read()
# regex pattern
pattern = ".\*."
# check whether pattern is present in string or not
result = re.search(pattern, string)
if result != None:
print(True)
else:
print(False)
| true |
61f70e447fdee0f317ef90ec7fc649fafc5b8f7d | kmvinoth/Hackerrank | /Easy/lst_comprehension.py | 900 | 4.375 | 4 | """
Let's learn about list comprehensions! You are given three integers X,Y and Z
representing the dimensions of a cuboid along with an integer N.
You have to print a list of all possible coordinates given by i,j,k on a 3D grid where the sum of i+j+k
is not equal to N. Here 0<=i<=X; 0<=j<=Y; 0<=k<=Z;
Input Format
Four integers and each on four separate lines, respectively.
Constraints
Print the list in lexicographic increasing order. """
X = int(input())
Y = int(input())
Z = int(input())
N = int(input())
print([[i, j, k] for i in range(0, X+1) for j in range(0, Y+1) for k in range(0, Z+1) if i+j+k != N])
""" List using normal for loops"""
X = 1
Y = 1
Z = 1
N = 2
res = []
for x in range(0, X+1):
for y in range(0, Y+1):
for z in range(0, Z+1):
if x+y+z != N:
lst = [x, y, z]
res.append(lst)
print(res)
| true |
20e3fc287dae5c16e9ad0c0f1d63f5fec46723ec | zharinovaa/homework9 | /polish_notation.py | 1,056 | 4.1875 | 4 | equation = input('Введите выражение : ')
operations = equation.split()
if len(operations) != 3:
try:
raise Exception('Необходимо ввести только 3 аргумента')
except Exception as e:
print(e)
exit(0)
result = 'Результат не получен'
assert (operations[0] == '+') or (operations[0] == '-') or (operations[0] == '*') or (operations[0] == '/'), 'Вы ввели не тот операнд'
try:
if operations[0] == '+':
result = int(operations[1]) + int(operations[2])
elif operations[0] == '-':
result = int(operations[1]) - int(operations[2])
elif operations[0] == '*':
result = int(operations[1]) * int(operations[2])
elif operations[0] == '/':
result = int(operations[1]) / int(operations[2])
except(ZeroDivisionError):
print('На нуль делить нельзя!')
except(TypeError):
print('Операции применимы только к числам!')
print(result) | false |
7c194fe3d8c6a81286e733ac83e70504271b88df | xyz010/Leetcode | /101 Symmetric Tree.py | 741 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def check(self,leftSub, rightSub):
if leftSub == None and rightSub == None:
return True
elif leftSub != None and rightSub != None:
return leftSub.val == rightSub.val and self.check(leftSub.left, rightSub.right) and self.check(leftSub.right, rightSub.left)
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# we will now perform the recursive function
return root == None or self.check(root.left, root.right)
| true |
4e82f8cd9bb1ea8ef60061ac84b47222963a086b | erik-vojtas/Practice-field | /passwordChecker.py | 1,676 | 4.21875 | 4 |
#Write a program to check the validity of password input by users.
#Conditions:
# At least 1 letter between [a-z]
# At least 1 number between [0-9]
# At least 1 letter between [A-Z]
# At least 1 character from [$#@]
# Minimum length of transaction password: 6
# Maximum length of transaction password: 12
def passwordChecker():
p = input("Please ENTER a password: ")
proved_l = False
proved_u = False
proved_d = False
proved_s = False
special_symbol = r'[$#@]'
for letter in p:
if letter.islower():
proved_l = True
if letter.isupper():
proved_u = True
if letter.isdigit():
proved_d = True
if letter in special_symbol:
proved_s = True
# print(proved_l, proved_u, proved_d, proved_s)
if len(p) < 6:
print(f'Minimum length of password is 6 characters.')
return passwordChecker()
elif len(p) > 12:
print(f'Maximum length of password is 12 characters.')
return passwordChecker()
elif proved_l == False:
print(f'Password has to contain at least 1 letter between [a-z].')
return passwordChecker()
elif proved_u == False:
print(f'Password has to contain at least 1 letter between [A-Z].')
return passwordChecker()
elif proved_d == False:
print(f'Password has to contain at least 1 digit between [0-9].')
return passwordChecker()
elif proved_s == False:
print(f'Password has to contain at least 1 special character between [$#@].')
return passwordChecker()
else:
print(f'Hureey! Your password {p} has been approved!')
passwordChecker() | true |
02117a734be84fa3c948446902ab867fbe88f014 | Temitayooyelowo/Udacity_Nanodegrees | /Data_Structures_and_Algorithms /Project_0/Task4.py | 1,529 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
# SET A: create set of people that make outgoing calls
# SET B: create set of people that send texts, receive texts, and receive incoming calls
# SET R: create set of results
# If person is in SET A but NOT in SET B then add to SET C
def solution():
people_outgoing_calls = set()
criteria = set()
results = set()
for call in calls:
people_outgoing_calls.add(call[0]) # make outgoing call
criteria.add(call[1]) # receive incoming calls
for text in texts:
criteria.add(text[0]) # send text
criteria.add(text[1]) # receive text
for caller in people_outgoing_calls:
if(caller not in criteria):
results.add(caller)
print("These numbers could be telemarketers: ")
for result in sorted(results):
print(f"{result}")
solution()
| true |
c98a4ff408969037fb8e038cc7cc94691faf1a61 | suruchee/python-basics | /Python-Practice/challenge2.py | 418 | 4.65625 | 5 | #Create a list of your favorite food items, the list should have minimum 5 elements.
#List out the 3rd element in the list.
#Add additional item to the current list and display the list.
#Insert an element named tacos at the 3rd index position of the list and print out the list elements.
food = ["rice","bread","milk","coffee","tea"]
print(food[2])
food.append("water")
print(food)
food.insert(3,"tacos")
print(food)
| true |
aaae65edbc24df9a01f2248b8fbb438933429114 | suruchee/python-basics | /Python-Practice/regularExpression.py | 1,600 | 4.1875 | 4 | import re
pattern = r"suru"
if re.match(pattern,"asuruchi"):
print('Match found')
else:
print('No match found')
if re.search(pattern,"asuruchi"):
print('Match found')
else:
print('No match found')
print(re.findall(pattern,"asuruchisuru"))
#find and replace
import re
string = "My name is John, Hi I'am John"
pattern = r"John"
newstring = re.sub(pattern,"Rob",string)
print(newstring)
#dot metacharacter
import re
pattern = r"gr.y"
if re.match(pattern, "gray"):
print("Match found")
#caret^(match must start from this particular point, here gr) and dollar metacharacter $
import re
pattern = r"^gr.y$"
if re.match(pattern,"grby"):
print("Match 1")
#character class
import re
pattern = r"[A-Z][a-z][0-9]"
if re.search(pattern,"AH6"):
print("Matched")
#star metacharacter
import re
pattern = r"eggs(bacon)*"
if re.match(pattern,"eggsbaconbacon"):
print("match found")
#plus meta character
import re
pattern = r"eggs(bacon)+"
if re.match(pattern,"eggsbaconbacon"):
print("match found")
#curly braces- repeating n numbers of times
import re
pattern = "ab{2}"
if re.match(pattern,"abb"):
print("match found")
#wildcard . a.b means we can place any character between a and b also matches (acbb)
import re
pattern = r"a.b"
if re.match(pattern,"acb"):
print("match found")
#optional? may or may not be occuring
#for - to be optional in opt-cdf
#pattern= opt-?cdf
################################
#string should be digits of length 5 (\d{5})
#string should be any non digits of length 5 (\D{5})
#string should be any alphanumeric character of length 5 (\w{5}) | false |
e9ef572e9c29db7165008c41587441ec14afebb6 | suruchee/python-basics | /Python-Practice/object-oriented-practice.py | 1,612 | 4.25 | 4 | class Students:
def __init__(self, name, contact):
self.name = name
self.contact = contact
def getdata(self):
print("Accepting data")
self.name = input("Enter name")
self.contact = input("Enter contact")
def putdata(self):
print("The name is" + self.name, "This is contact" + self.contact)
class ScienceStudent(Students):
def __init__(self, age):
self.age = age
def science(self):
print("I am science student")
John = ScienceStudent(20)
John.science()
John.getdata()
John.putdata()
#recursion
def factorial(x):
if(x == 1):
return 1
else:
return x*(factorial(x-1))
print(factorial(5))
#set
seta = {1,2,3,4,5,6}
setb = {4,5,6,7,8,9}
print(seta | setb)
print(seta & setb)
print(seta - setb)
#itertools
from itertools import count
for i in count(5):
print(i)
if i >= 20:
break
from itertools import accumulate, takewhile
numbers = list(accumulate(range(9)))
print(numbers)
print(list(takewhile(lambda x: x <= 10, numbers)))
#operator overloading
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.y
y = self.y + self.y
return Point(x,y)
def __str__(self):
return "({0},{1})".format(self.x, self.y)
point1 = Point(1,4)
point2 = Point(2,8)
print(point1 + point2)
#datahiding
class Myclas:
__hiddenvariable = 0
def add(self, increment):
self.__hiddenvariable += increment
print(self.__hiddenvariable)
objecttone = Myclas()
objecttone.add(5)
| true |
6604ec8bf1b16e8a1eba7fafae7b44e2e2b7ce43 | DanielleRenee/python_practices | /danielle-functions.py | 1,587 | 4.5625 | 5 | # Define your function below.
nums = [5, 12, 6, 7, 4, 9, 10]
not_all_nums = [4, 5, 6, 8, 'w', 'o', 'w']
def even_or_odd(lst, string='even'):
"""
Take two arguments, a list and a string indicating whether the user wants a
new list containing only the odd or even numbers. Return the user its new list.
"""
#set the parameter for an odd or even number by using modulo
#set default to even if not specified
#if asked for an odd list, only return a number from the input list that num % 2 would be 1
#play around with isinstance to check if list includes all integers, per python
#docs and stack overflow https://stackoverflow.com/questions/6009589/how-to-test-if-every-item-in-a-list-of-type-int
#per python docs on handling exceptions and also watched: https://www.youtube.com/watch?v=hrR0WrQMhSs
# if all(isinstance(item, int) for item in lst):
try:
even_lst = [x for x in lst if x % 2 == 0]
odd_lst = [x for x in lst if x % 2 == 1]
if string == 'odd':
#print odd_lst
return odd_lst
if string == 'even':
#print even_lst
return even_lst
except:
raise ValueError("Shoot, this function can only take a list of integers!")
# Call your function here (details on specifically how to call the function
# are in the assessment instructions.)
list_1 = even_or_odd(nums,)
print list_1
list_2 = even_or_odd(nums, 'odd')
print list_2
list_3 = even_or_odd(nums)
print list_3
print (list_1 == list_2)
print (list_1 == list_3)
#even_or_odd(not_all_nums,)
| true |
cddb25d783549db4eaf2e2daf6e7236b14489a4b | zachknig/Pirple-work | /main.py | 1,837 | 4.34375 | 4 | """
-- HOMEWORK 1 --
Zach Koenig, 07.22.19
This assignment involves solidifying knowledge gained with assigning and printing variables within a python framework by creating and pushing metadata variables concerning my favorite song, Moscow by Autoheart. All data was collected using Spotify.
"""
# variable definition
songTitle= "Moscow" # The title of the song
songArtist= "Autoheart" # the artist of the song
songGenre= "Indie Pop" # the genre of the song
albumTitle= "Punch" # the title of the song's album
yearReleased= 2013 # the year that the album was released
cityOfOrigin= "London" # the city that the band is from
countryOfOrigin= "England" # the country that the band is from
songDurationInMinutes= (3*(55/60)) # the duration of the song, converted to a float variable in minutes
songListens= 4584034 # the amount of listens, according to Spotify
monthlyListeners= 85321 # the band's monthly listeners, according to Spotify
bandMembers= 3 # the amount of people in the band
bandMales, bandFemales= 3,0 # the distribution of males vs. females in the band (assuming gender binaries for simplicity's sake)
chorusRepeats= 0 # the amount of times the chorus is played in the song. I listened to the song and added an iteration each time I heard the chorus
chorusRepeats += 1
chorusRepeats += 1
chorusRepeats += 1
# variable output
print(songTitle)
print(songArtist)
print(songGenre)
print(albumTitle)
print(yearReleased)
print(cityOfOrigin)
print(countryOfOrigin)
print(songDurationInMinutes)
print(songListens)
print(monthlyListeners)
print(bandMembers)
print(bandMales)
print(bandFemales)
print(chorusRepeats)
| true |
bbd16e7366ce210165e99e89a3fef964be3cf74b | CNM07/Python_Basics | /task1.py | 436 | 4.34375 | 4 | #Write a program which accepts a string as input to print "Yes" if the string is "yes", "YES" or "Yes", otherwise print "No".
#Hint: Use input () to get the persons input
word = input('Type a word:' )
if word == 'yes':
print('Yes')
elif word == 'Yes':
print('Yes')
elif word == 'YES':
print('Yes')
else:
print('No')
word = input('Type a word:').lower()
if word == 'yes':
print('Yes')
else:
print('No')
| true |
4f2b5b0f5cf8b0c98ab3ec8e8a0b593d10c1ba91 | JeanB762/python_cookbook | /find_commonalities_in_2_dict.py | 553 | 4.3125 | 4 | # You have two dictionaries and want to find out what they
# might have in common (same keys, same values, etc.).
# consider two dictionaries:
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
# To find out what the two dictionaries have in common, simply
# perform common set operations using the keys() or items() methods.
# Find keys in common
print(a.keys() & b.keys())
# Find keys in a that are not in b
print(a.keys() - b.keys())
# Find (key, value) pairs in common
print(a.items() & b.items()) | true |
964ac2ff4c3a83af8d0f61f5d42b51ccc844896a | eimearfoley/Carcassonne | /public_html/cgi-bin/Meeple.py | 1,231 | 4.15625 | 4 | class Meeple(object):
"""Creates a meeple Object
01/02/18 - Stephen and Euan
Initiates a Meeple Object.
player points to the player object which "owns" the Meeple
placed is a boolean which represents if the Meeple is placed on the board or not
colour is a string which represents the Meeple's colour, this is found using the Player's getColour method"""
def __init__(self,player):
self._player = player
self._placed = False
self._colour = self._player.getColour()
#Creates a string representation for a Meeple
def __str__(self):
outstr = ""
outstr += ("Meeple Colour:%s Meeple Player:%s Meeple Placed:%r"%(self._colour,self._player.getName(),self._placed))
return outstr
#Returns the colour of the meeple
def getColour(self):
return self._colour
#Retunrs the player using the meeple.
def getPlayer(self):
return self._player
#If a meeple is placed on a tile this sets placed to True
def place(self):
self._placed = True
#If a meeple is removed from a tile this sets placed to False
def take_back(self):
self._placed = False
| true |
ecba0f2ac4dfb7dc7ea6243fcfc0565b3aff7cdb | python-programming-1/homework-3-rantheway | /collatz.py | 445 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 17 14:48:23 2019
@author: shen
"""
def collatz(num):
while num != 1:
if num % 2 == 0:
num = num // 2
print(num)
elif num % 2 == 1:
num = 3 * num + 1
print(num)
try:
number = int(input('give me a number: '))
collatz(number)
except ValueError:
print('number only plz.') | false |
d3d704d800c6d5d9a99d6022f2ae3f97e61f3ed4 | chriskaringeg/Crimmz-pass-locker | /user_test.py | 1,887 | 4.15625 | 4 | import unittest
from user import User
class TestUser(unittest .TestCase):
'''
Tets case that defines test cases for the user class
behaviours
Args:
unittest.TestUser: TestUser class that helps in creating test cases
'''
def setUp(self):
'''
set up method to run before each test cases
'''
self.new_user = User('Chris' , 'Karinge')
def tearDown(self):
'''tear down method to clean up after every test
'''
User.user_list = [] #Returns an empty user list after every test
def test_init(self):
'''
Test to see if users are instanciated properties
'''
self.assertEqual(self.new_user.first_name , 'Chris')
self.assertEqual(self.new_user.last_name , 'Karinge')
def test_save_user(self):
'''
Test to see if users are saved in the user_list
'''
self.new_user.save_user() #saving new user
self.assertEqual(len(User.user_list) , 1)
def test_save_multiple_users(self):
'''
Test to see if multiple users can be saved
'''
self.new_user.save_user()
dummy_user = User('Loise' , 'Kimani') #new dummy user
dummy_user.save_user()
self.assertEqual(len(User.user_list) , 2)
def test_delete_user(self):
'''
Test to see if we can delete a user from user list
'''
self.new_user.save_user()
dummy_user = User('Loise' , 'kimani')
dummy_user.save_user()
self.new_user.delete_user() #Deleting a user from the user list
self.assertEqual(len(User.user_list) , 1)
def test_display_all_users(self):
'''
method that returns a list of all users saved
'''
self.assertEqual(User.display_users() , User.user_list)
if __name__ == '__main__':
unittest.main()
| true |
28f26d0f4c1f28a207901f5f19932badf4c2cc33 | Ritvik09/My-Python-Codes | /Python Codes/Calculator.py | 1,501 | 4.125 | 4 | # Print options (add,sub,mult,div)
# 1=add 2=sub 3=mult 4=div
# two inputs
while True:
print("Welcome User!")
print("Press 1 for Addition")
print("Press 2 for Subtraction")
print("Press 3 for Multiplication")
print("Press 4 for Division")
Operation = int(input())
if Operation ==1:
print("Enter two numbers:")
Number_1 = float(input())
print("+")
Number_2 = float(input())
total = Number_1 + Number_2
print(total)
elif Operation ==2:
print("Enter two numbers:")
Number_1 = float(input())
print("-")
Number_2 = float(input())
total = Number_1 - Number_2
print(total)
elif Operation ==3:
print("Enter two numbers:")
Number_1 = float(input())
print("*")
Number_2 = float(input())
total = Number_1 * Number_2
print(total)
elif Operation ==4:
print("Enter two numbers:")
Number_1 = float(input())
print("/")
Number_2 = float(input())
if Number_2 == 0:
print("Can't divide by zero")
else:
total = Number_1 / Number_2
print(total)
else:
print("Invalid")
print()
print("Continue?")
print("y for yes, n for no")
ch = input()
if ch =="n":
break
elif ch=="y":
print()
continue
| true |
1a6fcbe4f898b684fe086f26cdb05ea94dea8ffb | SACHSTech/ics2o-livehack1-practice-TheFaded-Greg-L | /minutes_days.py | 652 | 4.4375 | 4 | '''
-------------------------------------------------------------------------------
Name: minutes_days.py
Purpose: Converts Minutes to days, hours and minutes
Author: Lui.G
Created: 03/12/2020
------------------------------------------------------------------------------
'''
# Variables for the converter
minutes = int(input("How many minutes would you like to convert? "))
hours = minutes // 60
days = hours // 24
minutes_left = minutes - (hours * 60)
hours_left = hours - (days * 24)
# Output of the minutes to days, hours and days calculator
print(minutes, "minutes is equal to", days, "days", hours_left, "hours and", minutes_left, "minutes.") | true |
589c17376ba0bbcaed8bdd591a462b7a7359b2e2 | zqhhn/Python | /day07/code/_set.py | 793 | 4.34375 | 4 | """
创建一个set,需要提供一list作为输入集合
重复元素在set中会被自动过滤
通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果
通过remove(key)方法可以删除元素
set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:
set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,
因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”
"""
s = set([1,2,3])
print(s)
s = set([1,1,1,2,2,3,4,5,5])
s.add('2')
print(s)
s.remove('2')
print(s)
s1 = set([1,2,3])
s2 = set([2,3,4])
print(s1 & s2)
print(s1 | s2) | false |
b39323b5b8182ace36e3e81835963e3effd8c0e7 | zqhhn/Python | /day07/code/_dic.py | 853 | 4.28125 | 4 | """
把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
1.通过in判断key是否存在
2.dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
"""
user_dic = {"wang":18,"MR":19}
# print(user_dic["wang"])
user_dic["wang"] = 28
# print(user_dic["wang"])
# 把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
user_dic["zhong"] = 13
# print(user_dic["zhong"])
# 通过in判断key是否存在
# dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
if "zhong" in user_dic:
print(user_dic["zhong"])
print(user_dic.get('xxx'))
print(user_dic.get('xxx','xxx'))
# 要删除一个key,用pop(key)方法,对应的value也会从dict中删除:
user_dic.pop("zhong")
print(user_dic.get('zhong')) | false |
21f8aa6c4f01ad917bec22dbac6d4f65611c6073 | alexssantos/Python-codes | /Samples/Exercice/TP3-DR2/dr2-tp3-1.py | 331 | 4.15625 | 4 | myList = []
for element in range(5):
myList.append(element)
print(myList)
if 3 in myList:
myList.remove(3)
else:
print('myList do not have item 3')
if 6 in myList:
myList.remove(6)
else:
print('myList do not have item 6')
print(myList)
print('Length of myList: ', len(myList))
myList[-1] = 6
print(myList) | true |
7f41fdc174d611267eff4bcec042c39d2e1a426a | alexssantos/Python-codes | /Samples/DateTime/time-datetime-modules.py | 562 | 4.25 | 4 | import time
import datetime
# --------- TIME Module ---------
format = "%H:%M:%S" # Format
print(time.strftime(format)) # 24 hour format #
format = "%I:%M:%S" # Format
print(time.strftime(format)) # 12 hour format #
# Date with time-module
format = "%d/%m/%y"
print(time.strftime(format))
input()
# --------- DATETIME Module ---------
now = datetime.datetime.now()
now.hour
now.mintue
now.year
now.day
now.month
date = datetime.now()
print(str(date))
print(date.strftime('%Y/%m/%d %H:%M:%S'))
| true |
8302a5d49be84c32fc24cb201ab43ce159fa6385 | iBilbo/CodeWars | /alphabet_position.py | 806 | 4.28125 | 4 | """
kyu 8. INSTRUCTIONS. Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it. "a" = 1, "b" = 2, etc.
"""
def alphabet_position(text):
my_dict = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u":21, "v":22, "w": 23, "x": 24, "y": 25, "z": 26}
string_to_nums = []
for letter in text:
if letter.lower() in my_dict.keys():
string_to_nums.append(my_dict.get(letter.lower()))
else:
continue
print(' '.join([str(i) for i in string_to_nums]))
return ' '.join([str(i) for i in string_to_nums])
| false |
208a814d1ffce74cd1bd7eaedb39395b76ddba70 | huangichen97/SC101-projects | /SC101 - Github/Class&Object (Campy, Mouse Event)/draw_line.py | 1,837 | 4.125 | 4 | """
File: draw_line
Name:Ethan Huang
-------------------------
TODO:
This program opens a canvas and draws circles and lines in the following steps:
First, it detect if the click is a "first click" or a "second click".
If first click, the program will draw a hollow circle by SIZE.
If second click, the it will create a line from the circle to the new click,
and also delete the circle and then start a new round.
"""
from campy.graphics.gobjects import GOval, GLine
from campy.graphics.gwindow import GWindow
from campy.gui.events.mouse import onmouseclicked
SIZE = 10
is_first = True
circle_x = 0
circle_y = 0
circle = 0
window = GWindow()
def main():
"""
This program creates lines on an instance of GWindow class.
There is a circle indicating the user’s first click. A line appears
at the condition where the circle disappears as the user clicks
on the canvas for the second time.
"""
onmouseclicked(draw)
def draw(mouse):
global is_first, circle, circle_x, circle_y
if is_first is True:
# The click is a first click(1st, 3th, 5th, etc.)
# Should draw a circle on the mouse click
circle = GOval(SIZE, SIZE, x=mouse.x-SIZE/2, y=mouse.y-SIZE/2)
window.add(circle)
is_first = False # To make the next click a second click
circle_x = mouse.x - SIZE / 2
circle_y = mouse.y - SIZE / 2
else:
# The click is a second click(2nd, 4th, 6th, etc.)
# Should draw a line from the circle(created by the first click) to the new click
window.remove(circle)
the_line = GLine(circle_x, circle_y, mouse.x, mouse.y)
window.add(the_line)
is_first = True # To make the next click a first click again
if __name__ == "__main__":
main()
| true |
45b1b9758b34f9ce252ff72bb3334c2e3f60e3aa | huangichen97/SC101-projects | /SC101 - Github/Weather_Master/weather_master.py | 2,050 | 4.25 | 4 | """
File: weather_master.py
-----------------------
This program will implement a console program
that asks weather data from user to compute the
average, highest, lowest, cold days among the inputs.
"""
EXIT = -1
def main():
"""
This program asks weather data from user to compute the
average, highest, lowest, cold days among the inputs.
"""
print('stanCode "Weather Master 4.0"!')
data = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)? '))
if data == EXIT:
# No temperatures were entered.
print('No temperatures were entered.')
else:
# The first data was entered.
highest = data
# The highest temperature.
lowest = data
# The lowest temperature.
sum_temperature = data
# The SUM of the temperatures.
amount_of_data = 1
# Pieces of data users input.
average = float(sum_temperature / amount_of_data)
# The average temperature.
if data < 16:
# Check whether the first data is a cold day.
cold_day = 1
else:
cold_day = 0
while True:
# The program will keep the loop until users input "EXIT".
data = int(input('Next Temperature: (or ' + str(EXIT) + ' to quit)? '))
if data == EXIT:
# The user exited from the program.
break
else:
if data > highest:
highest = data
if data < lowest:
lowest = data
if data < 16:
cold_day += 1
sum_temperature += data
amount_of_data += 1
average = float(sum_temperature / amount_of_data)
print('Highest temperature = ' + str(highest))
print('Lowest temperature = ' + str(lowest))
print('Average = ' + str(average))
print(str(cold_day) + ' cold day(s)')
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
| true |
861133ebd916dd067df917638a681321503ce0e3 | Vazkito/Paquetes | /factorial_de_un_numero.py | 214 | 4.125 | 4 |
def factorial(numero1):
numero=int(numero1)
resultado=numero
while numero>1:
resultado=resultado*(numero-1)
numero=numero-1
print resultado
| false |
b06c56dbe88b9e6e56bab775d6ad4a119e97af19 | dhyani21/Hackerrank-30-days-of-code | /Day 3: Intro to Conditional Statements.py | 480 | 4.375 | 4 | #Given an integer,n , perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
n = int(input())
if(n%2 != 0):
print("Weird")
else:
if(n in range(2,6)):
print("Not Weird")
elif(n in range(6,21)):
print("Weird")
else:
print("Not Weird")
| false |
9b5bf68a2f25bfdb2a276fbaa481d28859a9acdf | dhyani21/Hackerrank-30-days-of-code | /Day 25: Running Time and Complexity.py | 576 | 4.1875 | 4 | '''
Task
A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given a number, n, determine and print whether it is Prime or Not prime.
'''
for _ in range(int(input())):
num = int(input())
if(num == 1):
print("Not prime")
else:
if(num % 2 == 0 and num > 2):
print("Not prime")
else:
for i in range(3, int(num**(1/2))+1, 2):
if num % i == 0:
print("Not prime")
break
else:
print("Prime")
| true |
fe6db5c4e41116d07e7d1c2990fe6ec5fd59d29f | Cathryne/Python | /ex12.py | 581 | 4.34375 | 4 | # Exercise 12: Prompting People
# http://learnpythonthehardway.org/book/ex12.html
# request input from user
# shorter alternative to ex11 with extra print ""
height = float(raw_input("How tall are you (in m)? "))
weight = int(raw_input("How many kilograms do you weigh? "))
print "So, you're %r m tall and %d kg heavy." % (height, weight)
# shorter without "BMI" helper variable in ex11: calculate directly after print, even without string formatting
print "That makes your BMI round about:", round(weight / ( height * height ), 1) # round(x, n) rounds x to n decimal places | true |
a4d1185302940515a0e84701c6b485ff7d8e7eae | Cathryne/Python | /ex39a.py | 1,843 | 4.59375 | 5 | # Exercise 39: Dictionaries, Oh Lovely Dictionaries
# http://learnpythonthehardway.org/book/ex39.html
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacks onville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
# accessing values in dictionary via keys: dict['key'] returns 'value'
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# Because value in one dict can be key in another, nested accessing is possible
# dict1[dict2['key2']] equals:
# value2 = dict2['key2']
# value1 = dict1['value2']
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# print every state abbreviation
print '-' * 10
for state, abbrev in states.items(): # iterators = keys in dictionary; items() returns dict contents
print "%s means %s" % (abbrev, state)
# print every city in state
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
print "State %s means %s which contains %s." % (abbrev, state, cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print "Sorry, no Texas."
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
| false |
e8b2fd46e39711a75e83f590a86ffa5433116a1e | Cathryne/Python | /ex38sd6c.py | 2,251 | 4.6875 | 5 | # Exercise 38: Doing Things To Lists
# http://learnpythonthehardway.org/book/ex38.html
# Study Drill 6: other examples of lists and what do do with them
# comparing word lists
# quote examples for testing
# Hamlet = "To be, or not to be, that is the question."
# https://en.wikipedia.org/wiki/To_be,_or_not_to_be#Text
# Crusoe = "Thus fear of danger is ten thousand times more terrifying than danger itself."
# https://www.goodreads.com/quotes/318230-thus-fear-of-danger-is-ten-thousand-times-more-terrifying
# functionalised listing of character name & quote words into list
def make_list(character, quote):
import string
quote_list = [character]
word_list = quote.translate(None, string.punctuation)
word_list = word_list.split(' ')
print "\tOK, so %s said: " % character, word_list
for i in range(len(word_list)):
last_word = word_list.pop()
quote_list.append(last_word)
i =+ 1
# print quote_list
return quote_list
print "\tLet's play a literature game! You are going to tell me 2 famous quotes and I'm going to tell you, which words they have in common."
character1 = str(raw_input("\tWho shall the 1st quote be from? "))
quote1 = str(raw_input("\tAnd what did they say? "))
quote1_list = make_list(character1, quote1)
character2 = str(raw_input("\tNow, who shall the 2nd quote be from? "))
quote2 = str(raw_input("\tAnd the 2nd one? "))
quote2_list = make_list(character2, quote2)
# determine longer quote & assign
if len(quote1_list) <= len(quote2_list):
reticent = character1
fewer_words = quote1
shorter_list = quote1_list
verbose = character2
more_words = quote2
longer_list = quote2_list
else:
reticent = character2
fewer_words = quote2
shorter_list = quote2_list
verbose = character1
more_words = quote1
longer_list = quote1_list
print "\tIn other words, %s was reticent in saying:" % reticent, fewer_words
print "\tWhile %s was verbose:" % verbose, more_words
# compare quote lists & convert result to new list
plagiates = set(quote1_list).intersection(quote2_list)
plagiates = list(plagiates)
# check if plagiates exist & display
if len(plagiates) != 0:
print "\tHa! Either %s or %s plagiarised the words from the other:" % (character1, character2), plagiates
else:
print "\tNo plagiate words found!"
| true |
88e7900015a7c199e6e605beb15189e211af78d0 | Cathryne/Python | /ex03.py | 1,550 | 4.21875 | 4 | # Exercise 3: Numbers and Math
# http://learnpythonthehardway.org/book/ex3.html
# general advice: leave space around all numbers & operators in mathematical operations, to distinguish from other code & esp. negative numbers
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
# , comma forces calculation result into same line
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# result of mathematical operation is printed directly; "qoutes" only for strings
# order PEMDAS (Parentheses, Exponents, Multiplication, Division, Addition & Subtraction)
# modulo operator % returns remainder after division
print "Is it true that 3 + 2 < 5 - 7 ?"
print 3 + 2 < 5 - 7 # Boolean statement returns True or False
print "What is 3 + 2 ?", 3 + 2
print "What is 5 - 7 ?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
# Study Drill 5: Rewrite to use floating point numbers so it's more accurate (hint: 20.0 is floating point).
# appending decimal point & 0 to each number
# Also works with only relevant ones?
print "And now the calculations again with floating points."
print "Hens", 25 + 30 / 6.0 # no effect, because 30 can already be completely divided by 6
print "Roosters", 100 - 25 * 3 % 4.0 # no effect because remainder of 75 / 3 = 72 is the integer 3
print "Eggs:", 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4.0 + 6 # effect, because 1 / 4.0 = 0.25
| true |
71d9d2c25a82558c813523cd9c7a935ffcbf5d78 | Cathryne/Python | /ex19sd3.py | 1,477 | 4.21875 | 4 | # Exercise 19: Functions and Variables
# http://learnpythonthehardway.org/book/ex19.html
# Study Drill 3: Write at least one more function of your own design, and run it 10 different ways.
def milkshake(milk_to_blend, fruit_to_blend, suggar_to_blend):
"""
Calculates serving size and prints out ingredient amounts
for milkshake.
"""
servings = int(raw_input("Oh yeah, I forgot! For how many servings shall all this be? "))
milk_to_serve = servings * milk_to_blend
fruit_to_serve = servings * fruit_to_blend
suggar_to_serve = servings * suggar_to_blend
print "You'll need %d g fruit, %d mL milk and %d g of suggar. Will it blend?!" % (fruit_to_serve, milk_to_serve, suggar_to_serve)
milk = 200
fruit = 50
suggar = 10
print "\nLet's make a milkshake! I know this recipe: Blend %d mL milk, %d g fruit and %d g suggar in a blender. However, you should adjust something..." % (milk, fruit, suggar)
# get recipe modifiers from user; can be negative
fruitiness = float(raw_input("... Like the fruitiness! How many % more or less do you want? "))
sweetness = float(raw_input("Same for the sweetness: "))
print "\n\nResults calculated in function call:"
milkshake(milk, fruit * (1 + (fruitiness / 100)), suggar * (1 + (sweetness / 100)))
print "\n\nResults calculated via helper variables:"
milk_to_blend = milk
fruit_to_blend = fruit * (1 + (fruitiness / 100))
suggar_to_blend = suggar * (1 + (sweetness / 100))
milkshake(milk_to_blend, fruit_to_blend, suggar_to_blend) | true |
42f65b2819021a0201c2ce3ee82ba39318beb466 | RahulSundar/DL-From-Scratch | /MLP.py | 1,821 | 4.1875 | 4 | import numpy as np
#import matplotlib.pyplot as plt
'''This is a code to implement a MLP using just numpy to model XOR logic gate.Through this code, one can hope to completely unbox how a MLP model is setup.'''
# Model Parameters
'''This should consist of the no. of input, output, hidden layer units. Also, no.of inputs and outputs. '''
N_HiddenLayers = 1
Total_layers = 3
N_training = 4
Ni_units = 2
Nh_units = 2
No_units = 1
#Training dataset
'''Here we also define training examples.'''
#input arrays
x = np.zeros((N_training, Ni_units))
x[:,0] = [0,1,0,1]
x[:,1] = [0,1,1,0]
# Target Values
target = np.zeros((N_training, No_units))
target[:,0] = [0,0,1,1]
#hidden layer
h = np.zeros((N_training,Nh_units))
#Output layer
y = np.zeros((N_training, No_units))
#Weights and biases
'''No. of weight matrices/biases a Total_layers - 1 = 2'''
W1 = np.ones((Nh_units, Ni_units))/2
W2 = np.ones((No_units, Nh_units))/2
b1 = -np.ones((Nh_units, 1))*0.5
b2 = -np.ones((No_units, 1))
#Activation function:
def sigmoid(z):
return 1/(1+np.exp(-z))
def binary_threshold(z):
return np.where(z>0, 1,0)
#Model: MLP (Simplest FFNN)
'''The model is set up as sequential matrix multiplications'''
'''Activation applied only on hidden layers as of now. Input layer's activation function is identity.'''
'''pre activation for input layer'''
z1 = np.matmul(x,np.transpose(W1)) + np.matmul(np.ones((N_training,1)), np.transpose(b1))
'''Activation for hidden layer'''
h = np.where(z1 >0, 1, 0)
'''Pre - activation of output layer '''
z2 =np.matmul(x,np.transpose(W2)) + np.matmul(np.ones((N_training,1)), np.transpose(b2))
'''Activation for output layer'''
y = np.where(z1 >0, 1, 0)
#Loss Function
'''Here, we shall be using mean squared error loss as the loss function'''
J = np.sum((y-target)**2)/N_training
print(J)
| true |
c2b21f2737be09db89a51add64f1d86907b28c00 | arsenijevicn/Python_HeadFirst | /chapter4/vsearch.py | 243 | 4.15625 | 4 | def search4vowels():
"""Displays any vowels found in asked-for word"""
vowels = set('aeiou')
word = input("Upisite rec: ")
found = vowels.intersection(set(word))
for vowels in found:
print(vowels)
search4vowels()
| true |
dac2f833ec8dda8eb23dcb88d4fed74f3b1848b8 | wolflion/Code2019 | /Python编程:从入门到实践/chap09类/chap09section02Car.py | 1,138 | 4.3125 | 4 | #9.2 使用类和实例
class Car():
def _init_(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 #类中的属性要有初始值,除了形参传递,也可以直接赋值
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title() # 这地方的return,是不是可以随便整,也无须啥返回类型验证?
def read_odometer(self): #读取新加的默认属性值
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
# 9.2.2 给属性指定默认值,(1)可以直接修改
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
#(2)写一个update()方法
#(3)还是写一个方法,进行递增
| false |
a55318bd90912a236a47efdf4d5dfcecc24ea371 | xiepf1101/python_study | /workspaceDemo/parentChild.py | 903 | 4.21875 | 4 | #coding=utf-8
#类的继承
class Parent:
parentAttr = 100
def __init__(self):
print("i am parent")
def parentMethod(self):
print("parent method")
def myMethod(self):
print("parentMethod")
def setAttr(self,attr):
Parent.parentAttr = attr
def getAttr(self):
print("parentAttr:",Parent.parentAttr)
#继承 className(ParentClassName1,ParentClassName2,...)
class Child(Parent):
def __init__(self):
print("i am child")
def childMethod(self):
print("child method")
def myMethod(self):
print("childMethod")
c = Child()
c.childMethod()
#父类方法
c.parentMethod()
c.setAttr(123)
c.getAttr()
#重载父类myMethod方法
c.myMethod()
#issubclass(sub,sup) 判断sub类和sup类间的关系 sub继承sup则返回True
print(issubclass(Child,Parent))
| false |
4dcb541a4c110aee3f795e990b3f096f5d00014d | AyushGupta22/RandomNumGenerator | /test.py | 749 | 4.25 | 4 | from rand import random
#Testing our random function by giving min , max limit and getting output as list and then compute percentage of higher number for reference
print('Enter min limit')
min = int(input())
print('Enter max limit')
max = int(input())
while max <= min:
print('Wrong max limit\nEnter Again: ')
max = int(input())
print('Want to generate more than one number input Y')
ch = input()
n = 1
if ch == 'Y' or ch == 'y':
print("input number of random no. you want to generate")
n = int(input())
res = random(min,max,n)
print('random numbers are :- ',res,sep='\n',end='\n')
greater = [x for x in res if x > min+((max-min)/2)]
print('percentage of higher numbers out of n =',n,' is ',len(greater)/n*100)
| true |
5a0f54795e5b2777ebe9b2e9fdbdb07ee7db5e33 | adilarrazolo83/lesson_two_handson | /main.py | 714 | 4.28125 | 4 | # Part 1. Create a program that will concatenate string variables together to form your birthday.
day = "12"
month = "October"
year = "1983"
my_birthday = month + " " + day + "," + year
print(my_birthday)
# Part 2. Concatenate the variables first, second, third, and fourth and set this concatenation to the variable final: this is a test
first = "happy"
second = "birthday"
third = "to"
fourth = "you"
final = first + " " + second + " " + third + " " + fourth
print(final.upper())
# Part 3.
age = 15
if age >= 10:
print("Not permitted")
elif age >= 15:
print("Permitted with a parent")
elif age >= 18:
print("Permitted with anyone over 18")
else:
print("Permitted to attend alone")
| true |
96dd3709ac413db258d3ab38be0bd957b51c117a | ktgnair/Python | /day_2.py | 602 | 4.3125 | 4 | #Datatypes
#String
#Anything inside a "" is considered as string
print("Hello"[1]) #Here we can find at position 1 which character is present in word Hello
print("1234" + "5678") #Doing this "1234" + "5678" will print just the concatenation of the two strings
print("Hello World")
#Integer
print(1234 + 5678) #For Integer just type the number. Here + means it will add the numbers
#Usually we will write a large number like 10000000 in real world as 1,00,00,000 for human readable format, that can be done in python using _
print(1_00_00_000 + 2)
#Float
print(3.1456)
#Boolean
True
False | true |
b3b3a3063b53e18e792d25c07f74d7a4d8441905 | ktgnair/Python | /day_10.py | 1,362 | 4.34375 | 4 | # Functions with Outputs.
# In a normal function if we do the below then we will get an error as result is not defined
# def new_function():
# result = 3*2
# new_function()
# print(result)
# But using 'return' keyword in the below code we are able to store the output of a function i.e Functions with Outputs
def my_function():
result = 3 * 2
return result
output = my_function()
print(output)
# String title()
# The title() function in python is used to convert the first character in each word to Uppercase and remaining characters to Lowercase in the string and returns a new string.
def format(f_name, l_name):
first_name = f_name.title()
last_name = l_name.title()
return f"{first_name} {last_name}"
name = format("kt","GOUtHAM")
print(name)
# Alternative way print(format("kt","GOUtHAM"))
# Multiple return values
# 'return' keyword tells the computer that the function is over and need to move further
# eg: The below code
# def format(f_name, l_name):
# if f_name == "" or l_name == "":
# return "The input is invalid"
# first_name = f_name.title()
# last_name = l_name.title()
# return f"{first_name} {last_name}"
# name = format(input("Enter the first name"), input("Enter the last name"))
# print(name)
# The above code will stop if the input is empty and will not run beyond the if statement. | true |
addc5679ff65e1454f5168d63ba1a72d098fbbe8 | ktgnair/Python | /day_8-2.py | 1,059 | 4.28125 | 4 | # Prime Number Checker
# You need to write a function that checks whether if the number passed into it is a prime number or not.
# e.g. 2 is a prime number because it's only divisible by 1 and 2.
# But 4 is not a prime number because you can divide it by 1, 2 or 4
user_input = int(input("Enter the number of your choice "))
def prime_checker(number):
count = 0
for n in range(1,number+1):
if(number % n == 0):
count += 1
print(count)
if(count == 2): # The count should be 2 because a number is prime if its divisible either by 1 or by the number itself. So only 2 time that condition occurs.
print(count)
print("It's a prime number")
else:
print("It's not a prime number")
prime_checker(number=user_input)
# Alternative Way
# def prime_checker(number):
# is_Prime = True
# for n in range(2,number):
# if(number % n == 0):
# is_Prime = False
# if is_Prime:
# print("It's a prime number")
# else:
# print("It's not a prime number")
| true |
70ef560b7cc262f805a8b18c0fa269444276b665 | ktgnair/Python | /day_5-5.py | 1,685 | 4.1875 | 4 | # Password Generator Project
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
print("Welcome to the Password Generator Program ")
total_letters = int(input("How many letters would you like in your Password?\n"))
total_numbers = int(input("How many numbers would you like in your Password?\n"))
total_symbols = int(input("How many symbols would you like in your Password?\n"))
password1 = random.sample(letters,total_letters) #Will return a random sample of the mentioned length - total_letters
password2 = random.sample(numbers,total_numbers)
password3 = random.sample(symbols,total_symbols)
final_password = password1 + password2 + password3 #By doing this we will get the password but it will of fixed order letters + numbers + symbols
final_password_new = random.sample(final_password, len(final_password)) #By doing this step we are again finding the random list out of the above final_password(means it will give output in unknow format, which will make the password tough to crack)
final_password_string = "" #Empty string to concatenate the string inside the for loop
for i in final_password_new:
# Take one value from the list and concatenate it in the empty string, and finally we will have the whole list in one single string.
final_password_string += i
print(f"Your Password is: {final_password_string}") | true |
9d2c5436378129d0f27f90a77aea9dd6249bab94 | ktgnair/Python | /day_4-4.py | 1,247 | 4.71875 | 5 | # Treasure Map
# Write a program which will mark a spot with an X.
# You need to add a variable called map.This map contains a nested list.
# When map is printed this is what the nested list looks like:
# ['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️'],['⬜️', '⬜️', '⬜️']
# Format the three rows into a square, like this:
# ['⬜️', '⬜️', '⬜️']
# ['⬜️', '⬜️', '⬜️']
# ['⬜️', '⬜️', '⬜️']
# Write a program that allows you to mark a square on the map using a two-digit system.
# The first digit is the vertical column number and the second digit is the horizontal row number. e.g.:23
# ['⬜️', '⬜️', '⬜️']
# ['⬜️', '⬜️', '⬜️']
# ['⬜️', 'X', '⬜️']
# For the below image in the list just go to https://emojipedia.org/empty-page/ and copy that emoji and paste it in the code
row1 = ["🗌", "🗌", "🗌"]
row2 = ["🗌", "🗌", "🗌"]
row3 = ["🗌", "🗌", "🗌"]
treasure_map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
column_no = int(position[0])
row_no = int(position[1])
treasure_map[row_no - 1][column_no - 1] = "❌"
# print(treasure_map)
print(f"{row1}\n{row2}\n{row3}") | true |
27e08761ba250ff3ddf19c454df05fdf0acade2d | Alexanderdude/PythonInvestments | /finance_calculators.py | 2,651 | 4.28125 | 4 | import math # Imports the math module
print("\n" + "Choose either 'investment' or 'bond' from the menu below to proceed: " + "\n" + "\n" +
"investment \t - to calculate the amount of interest you'll earn on interest" + "\n" +
"bond \t \t - to calculate the amount you'll have to pay on a home loan") # Displays text for the user
sType = input("\n" + "Please enter your answer here: ") # Gets the users input
sType = sType.upper() # Makes the input all in capital letters
print("\n")
if sType == "INVESTMENT" : # If the user entered investment
rOriginal = float(input("\n" + "Please enter the amount of money you are depositing: ")) # User input
rInRate = float(input("\n" + "Please enter the interest rate: ")) # User input
iYears = int(input("\n" + "Please enter the amount of years the money will be deposited: ")) # User input
sInType = input("\n" + "Will it be compound or simple interest?: ") # User input
sInType = sInType.upper() # Makes the input all in capital letters
if sInType == "SIMPLE" : # If user typed simple
rTotal = rOriginal * (1 + ((rInRate / 100) * iYears))
print("\n \n" + "Wow, you will start off with R" + str(rOriginal) + " and after " + str(iYears) +
" years you will get a total of R" + str(rTotal) + ". That is a R" + str(rTotal - rOriginal)
+ " increase!" )
elif sInType == "COMPOUND" : # If user typed compound
rTotal = rOriginal * ((1 + (rInRate / 100))) ** iYears # Compound interest formulae
print("\n \n" + "Wow, you will start off with R" + str(rOriginal) + " and after " + str(iYears) +
" years you will get a total of R" + str(rTotal) + ". That is a R" + str(rTotal - rOriginal)
+ " increase!" )
else :
print("\n \n" + "Please select either 'simple' or 'compound' ") # Error message
elif sType == "BOND" :
rVal = float(input("\n" + "Please enter the value of your house: ")) # User input
rInRate = float(input("\n" + "Please enter the interest rate: ")) # User input
iMonth = int(input("\n" + "Please enter the number of months you want to take to repay the bond: ")) # User input
rTotal = (((rInRate / 100) / 12) * rVal)/(1 - ((1 + ((rInRate / 100) / 12)) ** (-iMonth))) # bond interest formulae
print("\n \n" + "You will have to pay R" + str(rTotal) + " each month for a total of " + str(iMonth) + " months.")
else :
print("\n \n" + "Please select either 'bond' or 'interest' ") # Error message
| true |
c26242104a494b3a38fb578e1d437cc6853dd2ae | Jlemien/Beginner-Python-Projects | /Guess My Number.py | 893 | 4.4375 | 4 | 7"""Overview: The computer randomly generates a number.
The user inputs a number, and the computer will tell you if you are too high, or too low.
Then you will get to keep guessing until you guess the number.
What you will be Using: Random, Integers, Input/Output, Print, While (Loop), If/Elif/Else"""
from random import randint
number = randint(0,10000000)
print("You need to guess what number I'm thinking of.")
guess = int(input("What number would you like to guess? "))
while 1 == 1:
if guess == number:
print("Hooray! You guessed it right!")
break
elif guess < number:
print("The number you guessed is too small.")
guess = int(input("Guess again. What number would you like to guess? "))
elif guess > number:
print("The number you guessed is too big.")
guess = int(input("Guess again. What number would you like to guess? "))
| true |
8af705ec7631c1bfa3d9e9f10e262dc153103ead | Jlemien/Beginner-Python-Projects | /University of Michigan Python Projects/Population.py | 888 | 4.28125 | 4 | print("I will give you an estimate for what the US population will be in the future")
year = input("what year would you like a prediction for? ")
years_into_the_future = float(year) - 2017
print("That is about", years_into_the_future, "years in the future.")
current_population = 307357870
#I estimate that in X years the US population will be about Y.
#every 7 seconds, a birth
birth_every_7_seconds = years_into_the_future * 365 *24 * 60 * 60 / 7
#every 13 seconds, a death
death_every_13_seconds = years_into_the_future * 365 *24 * 60 * 60 / 13
#every 35 seconds, a new immigrant
new_immigrant_every_35_seconds = years_into_the_future * 365 *24 * 60 * 60 / 35
predicted_population = current_population + (birth_every_7_seconds) + (new_immigrant_every_35_seconds) - (death_every_13_seconds)
print("The population of the US in the year", year, "will be about", predicted_population) | false |
ff91ad850f74a826a95f395363dd00cf867c0990 | Jlemien/Beginner-Python-Projects | /University of Michigan Python Projects/Debt.py | 2,390 | 4.3125 | 4 | #http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/01_Beginnings/FirstWeekProjects/Debt/project01.pdf
#current debt is 19500000000000
#ask the user for the current national debt
current_national_debt = float(input("What is the current national debt of the USA? "))
#ask the user what denomination of bull they want to use
denomination = str((input("What denomination of US bill between 1 and 100 would you like to use? ")))
if denomination == str(1):
height_in_miles = current_national_debt / float(denomination) * 0.0043 / 15133980000
print("A stack of", denomination, "bills equal to the national debt would be", height_in_miles, "miles high.")
print("That would take you to the moon", height_in_miles / 238857 , "times.")
elif denomination == str(5):
height_in_miles = current_national_debt / float(denomination) * 0.0043 / 15133980000
print("A stack of", denomination, "bills equal to the national debt would be", height_in_miles, "miles high.")
print("That would take you to the moon", height_in_miles / 238857 , "times.")
elif denomination == str(10):
height_in_miles = current_national_debt / float(denomination) * 0.0043 / 15133980000
print("A stack of", denomination, "bills equal to the national debt would be", height_in_miles, "miles high.")
print("That would take you to the moon", height_in_miles / 238857 , "times.")
elif denomination == str(20):
height_in_miles = current_national_debt / float(denomination) * 0.0043 / 15133980000
print("A stack of", denomination, "bills equal to the national debt would be", height_in_miles, "miles high.")
print("That would take you to the moon", height_in_miles / 238857 , "times.")
elif denomination == str(50):
height_in_miles = current_national_debt / float(denomination) * 0.0043 / 15133980000
print("A stack of", denomination, "bills equal to the national debt would be", height_in_miles, "miles high.")
print("That would take you to the moon", height_in_miles / 238857 , "times.")
elif denomination == str(100):
height_in_miles = current_national_debt / float(denomination) * 0.0043 / 15133980000
print("A stack of", denomination, "bills equal to the national debt would be", height_in_miles, "miles high.")
print("That would take you to the moon", height_in_miles / 238857 , "times.")
else:
print("That isn't a denomination of US bill.")
| false |
a956f3b23892c56326cddaccf4b14b75e660706b | DKojen/HackerRank-Solutions | /Python/Text_wrap.py | 552 | 4.15625 | 4 | #https://www.hackerrank.com/challenges/text-wrap/problem
#You are given a string and width .
#Your task is to wrap the string into a paragraph of width .
import textwrap
string = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'
max_width = 4
def wrap(string, max_width):
return textwrap.fill(string,max_width)
if __name__ == '__main__':
result = wrap(string, max_width)
print(result)
#or without using textwrap:
def wrap(string, max_width):
return "\n".join([string[i:i+max_width] for i in range(0, len(string), max_width)])
| true |
275a568b7ccd4adb102c768fd74f8b8e78a04515 | nickborovik/stepik_python_advanced | /lesson1_3.py | 1,237 | 4.21875 | 4 | # functions
"""
def function_name(argument1, argument2):
return argument1 + argument2
x = function_name(2, 8)
y = function_name(x, 21)
print(y)
print(type(function_name))
print(id(function_name))
"""
"""
def list_sum(lst):
result = 0
for element in lst:
result += element
return result
def sum(a, b):
return a + b
y = sum(14, 29)
z = list_sum([1, 2, 3])
print(y)
print(z)
"""
# stack in python
"""
def g():
print("I am function g")
def f():
print("I am function f")
g()
print("I am function f")
print("I am outside of any function")
f()
print("I am outside of any function")
"""
# task 1 - write program
# my code
"""
def closest_mod_5(x):
x = int(x)
while x % 5:
x += 1
return x
"""
# my optimized code
"""
def closest_mod_5(x):
return (x + 4) // 5 * 5
y = int(input())
print(closest_mod_5(y))
"""
# fibonacci
"""
def fib(x):
if x == 0 or x == 1:
return 1
else:
return fib(x - 1) + fib(x - 2)
y = fib(5)
print(y)
"""
# task 2 - write program
"""
def C(n, k):
if k == 0:
return 1
elif n < k:
return 0
else:
return C(n - 1, k) + C(n - 1, k - 1)
n, k = map(int, input().split())
print(C(n, k))
""" | true |
f85cb21075e1320782d29d9f0b0063d95df2bc23 | shreyas710/Third-Year-Programs-Computer-Engineering-SPPU | /Python & R programming/prac5.py | 474 | 4.21875 | 4 | #Title: Create lambda function which will return true when no is even:
import mypackage.demo
mypackage.demo.my_fun()
value=lambda no:no%2==0
no=input("Enter the no which you want to check : ")
print(value(int(no)))
#title:filter function to obtain or print even no or print even no
num_list=[1,2,3,4,5]
x=list(filter(lambda num:(num%2==0),num_list))
print(x)
#Title:create a map function to multiply no an group by 5
x=list(map(lambda num:(num*5),num_list))
print(x)
| true |
b4fc0ae52373293a9d87f80a7e7124d8f32c927c | arashafazeli/tester-py2 | /main.py | 1,287 | 4.21875 | 4 | print('hello world from\n Dr.krillzorz')
print('Now iam down here\n')
hello = 'This is a string inside a variable\n'
universe = 42
foo = '42'
bar = 1.25
space = ' '
d = 'world' ,bar
#print(hello)
#print(type(hello))
#print(world)
#print(type(world))
#print(foo)
#print(type(foo))
#print(bar)
#print(type(doob))
#print (bar+universe +int(foo))
hello = 'This is a string inside a variable'
universe = 42
bar = 1.25
foo = '42'
space = ' .:. '
# print(type(hello))
# print(type(world))
# print(type(d))
# print('hello' + space + 'world' + space + str(bar))
# print(type(bar))
#skriv en funktionsdefinition som tar in en parameter
#parametern består av en sträng som består av en fråga
#funktionen ska stäla frågan till användaren
#det användaren svarar skall konverteras till int eller float
#samt retuneras tillbaka till anropande kod
def ask_user (prompt):
#print('The funkytion was called with argument {prompt}')
s = input(prompt)
#print(type(s))
return eval(s)
answer = ask_user('please enter a length in meters')
print(f'Then user answered {answer} ')
#s = eval(input('please enter a distance in cm: '))
#print(s)
#print(type(s))
#area = s ** 2
print('The area of a square with side ' + str(s) +
' cm is equal to ' + str(area) + ' cm^2') | false |
f7c25f4592050bcb9df83d514d2f8df110c5d449 | w-dayrit/learn-python3-the-hard-way | /ex21.py | 1,595 | 4.15625 | 4 | def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
print("Let's do some math with just functions!")
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq,2))))
print("That becomes: ", what, "Can you do it by hand?")
# Study Drills
# 1. If you aren’t really sure what return does, try writing a few of your own functions and have them return some values. You can return anything that you can put to the right of an =.
# 2. At the end of the script is a puzzle. I’m taking the return value of one function and using it as the argument of another function. I’m doing this in a chain so that I’m kind of creating a formula using the functions. It looks really weird, but if you run the script, you can see the results. What you should do is try to figure out the normal formula that would recreate this same set of operations.
# 3. Once you have the formula worked out for the puzzle, get in there and see what happens when you modify the parts of the functions. Try to change it on purpose to make another value.
# 4. Do the inverse. Write a simple formula and use the functions in the same way to calculate it | true |
e3cd5279375fc9b78d13676b76b98b76768f38a7 | umaralam/python | /method_overriding.py | 426 | 4.53125 | 5 | #!/usr/bin/python3
##Extending or modifying the method defined in the base class i.e. method_overriding. In this example is the call to constructor method##
class Animal:
def __init__(self):
print("Animal Constructor")
self.age = 1
class Mammal(Animal):
def __init__(self):
print("Mammal Constructor")
self.weight = 2
super().__init__()
def eat(self):
print("eats")
m = Mammal()
print(m.age)
print(m.weight)
| true |
019b266b1aa9f3ce7251acb5959f93f175df1d9d | umaralam/python | /getter_setter_property.py | 1,555 | 4.3125 | 4 | #!/usr/bin/python3
class Product:
def __init__(self, price):
##No data validation in place##
# self.price = price
##Letting setter to set the price so that the validation is performed on the input##
# self.set_price(price)
##Since using decorator for property object our constructor will get modified as##
self.price = price
##price getter##
# def get_price(self):
# return self.__price
##price setter
# def set_price(self, value):
# if value < 0:
# raise ValueError("Price can not be negative.")
# self.__price = value
##setting property for getter and setter of product price##
# price = property(get_price, set_price)
##With the above property implementation get_price and set_price is still directly accessible from outside. To avoid that we need to define
##property in a better way using decorator object rather than making getter and setter private using "__"##
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price can not be negative.")
self.__price = value
##Passed negative value. Python accepts it without validation##
product = Product(10)
##Directly accessing the price field to get the product price##
#print(product.price)
##getting price by calling getter since price field is no longer accessible directly##
#print(product.get_price())
##Instead of calling getter and setter we can call the property object to get and set the price like a regular field access##
#product.price = -1
print(product.price)
| true |
ad6fd41bd59eed17e8d504fcb6fdfa9d7da7f7c7 | ArsathParves/P4E | /python assingments/rduper.py | 326 | 4.15625 | 4 | #fname = input("Enter file name: ")
#fh = open(fname)
#inp=fh.read()
#ufh=inp.upper()
#sfh=ufh.rstrip()
#print(sfh)
## Read a file and print them the characters in CAPS and strip /n from right of the lines
fname = input("Enter file name: ")
fh = open(fname)
for lx in fh:
ly=lx.rstrip()
print(ly.upper())
| true |
8a9f103b3ff3222d1b2b207c30fed67fee1c1450 | ArsathParves/P4E | /python assingments/ex7-2.py | 872 | 4.25 | 4 | # 7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
# X-DSPAM-Confidence: 0.8475(eg)
# Count these lines and extract the floating point values from each of the lines and compute the average of those
# values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
count=0
sum=0.0
average=0.0
fh = open(fname)
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
pos = line.find('0')
num=line[pos:pos+6]
fnum=float(num)
count=count+1
sum=sum+fnum
average=sum/count
print(fnum)
#print('Total lines:',count)
#print('Total sum:',sum)
print('Average spam confidence:',average)
| true |
d7f4292809f3d59cb76f62bc9d3bce9d33e1f70e | Sngunfei/algorithms | /sword2offer/InversePairs.py | 2,392 | 4.21875 | 4 |
"""
给定一个数组,统计其内部的逆序对个数
归并排序
两个排好序的数组,如何统计逆序数?只需要每次复制的时候,把另一个数组中的剩余个数统计一下,
那么等复制完,这个数字就是答案了。那问题来了,如何得到两个排好序的数组呢?
"""
def mergeSort(nums, left, right):
"""
归并排序
:param nums:
:param left:
:param right:
:return:
"""
if left >= right:
return 0
mid = left + ((right - left) >> 1)
cnt_left = mergeSort(nums, left, mid)
cnt_right = mergeSort(nums, mid+1, right)
left_nums = nums[left:mid+1]
right_nums = nums[mid+1:right+1]
i = len(left_nums) - 1
j = len(right_nums) - 1
index = right
cnt = 0
while i >= 0 and j >= 0:
if left_nums[i] > right_nums[j]:
nums[index] = left_nums[i]
cnt += j + 1
i -= 1
else:
nums[index] = right_nums[j]
j -= 1
index -= 1
while j >= 0:
nums[index] = right_nums[j]
j -= 1
index -= 1
while i >= 0:
nums[index] = left_nums[i]
i -= 1
index -= 1
return cnt_left + cnt_right + cnt
def merge_sort(nums, left, right):
"""
原地归并排序
:param nums:
:param left:
:param right:
:return:
"""
if left == right:
return
mid = left + (right - left) >> 1
merge_sort(nums, left, mid)
merge_sort(nums, mid+1, right)
i = mid
j = right
index = right
ni, nj = nums[i], nums[j]
while i >= left and j >= mid + 1:
if ni > nj:
nums[index] = ni
i -= 1
ni = nums[i]
else:
nums[index] = nj
j -= 1
nj = nums[j]
index -= 1
while i >= left:
nums[index] = nums[i]
i -= 1
index -= 1
while j >= mid + 1:
nums[index] = nums[j]
j -= 1
index -= 1
def cnt_inverse_pairs(arr):
cnt = 0
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
cnt += 1
return cnt
if __name__ == '__main__':
arr = [7, 4, 6, 5, 1, 2, 3, 4, 7, 8, 9, 2, 10]
res = [0] * len(arr)
print(cnt_inverse_pairs(arr))
print(mergeSort(arr, 0, len(arr) - 1))
print(arr)
| false |
32836815b3d948376d26030dff4fe454c654b591 | nortonhelton1/classcode | /classes_and_objects (1)/classes_and_objects/customer-and-address.py | 1,103 | 4.4375 | 4 |
class Customer:
def __init__(self, name):
self.name = name
self.addresses = [] # array to represent addresses
class Address:
def __init__(self, street, city, state, zip_code):
self.street = street
self.city = city
self.state = state
self.zip_code = zip_code
customer = Customer("John Doe")
print(customer.addresses)
address = Address("1200 Richmond", "Houston", "TX", "77989")
another_address = Address("345 Harvin", "Houston", "TX", "77867")
# how to add address to a customer
customer.addresses.append(address)
customer.addresses.append(another_address)
# display customer and addresses
print(customer.name)
for address in customer.addresses:
print(address.street)
print(address.state)
#print(customer.addresses)
#customer.street = "1200 Richmond Ave"
#customer.city = "Houston"
#customer.state = "TX"
#customer.zip_code = "77890"
#Post
#Comment
#A single Post can have many comments
#Comment can belong to a Post
Walmart
- Paper
- Shirts
- Shoes
HEB
- Meat
- Chicken
Fiesta
- Fish
- Vegetables
| true |
05acb84502e7e62ea9da1088ee08c1c945652c71 | dylantzx/HackerRank | /30 Days Of Code/DictionariesAndMaps.py | 635 | 4.125 | 4 | ############################# Question ###########################
# https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
##################################################################
# Enter your code here. Read input from STDIN. Print output to STDOUT
count = int(input())
list_of_queries = [input().split() for i in range(count)]
phonebook = {name:number for name,number in list_of_queries}
while True:
try:
check_name = input()
if check_name in phonebook:
print(f"{check_name}={phonebook[check_name]}")
else:
print("Not found")
except:
break | true |
097588bb6e41bfb37381b95dc6955fcd349ad2c3 | zemi4/Python-tasks | /Sun Angle.py | 1,085 | 4.28125 | 4 | ''' определить угол солнца над горизонтом, зная время суток. Исходные данные: солнце встает на востоке в 6:00, что соответствует углу 0 градусов.
В 12:00 солнце в зените, а значит угол = 90 градусов. В 18:00 солнце садится за горизонт и угол равен 180 градусов.
В случае, если указано ночное время (раньше 6:00 или позже 18:00), функция должна вернуть фразу "I don't see the sun!".'''
def sun_angle(time):
a = int(time[0:2]) * 60 + int(time[3:5])
return "I don't see the sun!" if a > 1080 or a < 360 else (a - 360) * 0.25
if __name__ == '__main__':
print("Example:")
print(sun_angle("07:00"))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert sun_angle("07:00") == 15
assert sun_angle("12:15") == 93.75
assert sun_angle("01:23") == "I don't see the sun!"
| false |
c1f1c50534463aea935f74526059a3760f2bbfc7 | abbasjam/abbas_repo | /python/dev-ops/python/pythan-class/string14.py | 212 | 4.15625 | 4 | print ("String Manipulations")
print ("-------------------")
x=input("Enter the String:")
print ("Given String is:",x)
if x.endswith('.txt'):
print ("Yes!!!!!!!text file")
else:
print ("Not textfile")
| true |
5864a1d2a032b9379e2ce6118c2e77598116c81a | abbasjam/abbas_repo | /python/dev-ops/python/pythan-class/string7.py | 234 | 4.15625 | 4 | print ("String Manipulations")
print ("-------------------")
x=input("Enter the String:")
print ("Given String is:",x)
if x.isspace():
print ("String Contains only spaces ")
else:
print ("one or more chars are not spaces")
| true |
6ffce6b6ba40bad4d70bd8dc847cfcabc9dfdcbd | chapman-cs510-2017f/cw-03-sharonjetkynan | /sequences.py | 610 | 4.4375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def fibonacci(n):
"""
object: fibonacci(n) returns the first n Fibonacci numbers in a list
input: n- the number used to calculate the fibonacci list
return: retList- the fibonacci list
"""
if type(n) != int:
print(n)
print(":input not an integer")
return False
if n <= 0:
print(str(n)+"not a postive integer")
return False
f1=1
f2=1
retList=[]
for i in range (0,n):
retList.append(f1)
fn=f1+f2
f1=f2
f2=fn
return retList
| true |
f671a071f6f111ea4f63e2b6aea4dd8e1844d056 | KyleHu14/python-alarm-clock | /main.py | 1,704 | 4.28125 | 4 | import time
import datetime
def print_title() -> None:
# Prints the title / welcome string when you open the app
print('#' * 26)
print('#' + '{:^24s}'.format("Alarm Clock App") + '#')
print('#' * 26)
print()
def take_input() -> str:
# Takes the input from the user and checks if the input is correct
print('Enter Time in the Following Format : [Hours:Minutes:Seconds]')
print('Example (5 hours, 5 minutes, 60 seconds) : 5:5:60\n')
user_input_time = input('Enter Time: ')
while not _check_input(user_input_time):
print('[ERROR] : Incorrect input detected, please re-enter the time.')
user_input_time = input('Enter Time : ')
print()
return user_input_time
def _check_input(input_time : str) -> bool:
# When given a string, checks if the input fulfills the int:int:int format
if input_time.count(':') >= 4:
return False
if input_time.isalpha():
return False
if ':' in input_time:
for x in input_time.split(':'):
if x.isalpha():
return False
return True
def convert_time(input_time : str) -> int:
# Converts the input time in the format hour:min:sec and converts it to seconds
hours = int(input_time.split(':')[0])
minute = int(input_time.split(':')[1])
sec = int(input_time.split(':')[2])
return (hours * 60 * 60) + (minute * 60) + sec
def countdown(secs : int) -> None:
while secs > 0:
print(datetime.timedelta(seconds=secs), end='\r')
time.sleep(1)
secs -= 1
def main() -> None:
print_title()
final_time = convert_time(take_input())
countdown(final_time)
main() | true |
97e49ed0257e6f87dd9dd55ccaa7034b2f50ca9f | foleymd/boring-stuff | /more_about_strings/advanced_str_syntax.py | 1,051 | 4.1875 | 4 | #escape characters
#quotation
print('I can\'t go to the store.')
print("That is Alice's cat.")
print('That isn\'t Alice\'s "cat."')
print("Hello, \"cat\".")
print('''Hello, you aren't a "cat."''')
#tab
print('Hello, \t cat.')
#newline
print('Hello, \n cat.')
print('Hello there!\nHow are you?\nI\'m fine!')
#backslash
print('Hello, \\ cat.')
#raw string (doesn't do escape characters)
print(r'Hello there!\nHow are you?\nI\'m fine!')
#triple quotes for multiline strings
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
print("""Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob""")
spam = """Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob"""
print(spam) #it keeps the new lines when it stores the variables
#strings uses indexes and slices and in/not in
hello = 'hello world'
print(hello[2])
print(hello[1:3])
print('world' in hello) #True
print('World' in hello) #False
| true |
185d9ce5496bb637090cae05cb093804d2170a36 | vishwaka07/phython-test | /formatting.py | 227 | 4.375 | 4 | name = "Krishna"
age = "18"
# serval ways to print the data
print("hello" + name + "your age is " + age)
#python v3
print("hello {} your age is {} ".format(name,age))
#python 3.6
print(f"hello {name} your age is {age}") | false |
7939df2c4af30d7527ab8919d69ba5055f43f7ce | vishwaka07/phython-test | /tuples.py | 1,048 | 4.46875 | 4 | # tuples is also a data structure, can store any type of data
# most important tuple is immutable
# u cannot update data inside the tuple
# no append, no remove, no pop, no insert
example = ( '1','2','3')
#when to use : days , month
#tuples are faster than lists
#methods that can be used in tuples : count,index, len function,slicing
#tuple with one element
num = (1,)
print(type(num))
# tuple without parenthesis "()"
guitar = 'yamaha','base'
print(type(guitar))
#tuple unpacking
guitarist = ('hello1','hello2','hello3')
name1,name2,name3 = (guitarist)
print(name1)
#list inside the tuple
#function returning two values means its gives output in tuple
#so we have to store data in two variable
def func(int1,int2):
add = int1 + int2
multiply = int1*int2
return add,multiply
add, multiply = func(2,3)
print(add)
print(multiply)
# tuple can be use with range as
num = tuple(range(1,11))
print(num)
#convert tuple into list
nums = list((1,2,3,4,5,6))
print(nums)
#convert tuple into str
nums1=str((1,2,3,4,5,6))
print(nums1) | true |
0b15fd9864c222c904eef1e7515b5dd125e05022 | Randheerrrk/Algo-and-DS | /Leetcode/515.py | 1,209 | 4.1875 | 4 | '''
Find Largest Value in Each Tree Row
------------------------------------
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Input: root = [1,2,3]
Output: [1,3]
Input: root = [1]
Output: [1]
Input: root = [1,null,2]
Output: [1,2]
Input: root = []
Output: []
'''
# Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
if(root==None) : return []
result = []
def bfs(root: TreeNode) :
q = [root]
nonlocal result
while q :
s = len(q)
levelMax = -math.inf
for i in range(s) :
temp = q.pop(0)
levelMax = max(temp.val, levelMax)
if(temp.left) : q.append(temp.left)
if(temp.right) : q.append(temp.right)
result.append(levelMax)
bfs(root)
return result
| true |
e6eada3e5ad01097e132123a75d6c2b3a134d977 | shulme801/Python101 | /squares.py | 451 | 4.21875 | 4 | squares = [value**2 for value in range(1,11)]
print(squares)
# for value in range(1, 11):
# # square = value ** 2
# # squares.append(square)
# squares.append(value**2)
# print(f"Here's the squares of the first 10 integers {squares}")
odd_numbers = list(range(1,20,2))
print(f"Here's the odd numbers from 1 through 20 {odd_numbers}")
cubes = [value**3 for value in range(1,21)]
print(f"\nHere's the cubes of the 1st 20 integers: {cubes}\n") | true |
0b9e29c79c892215611b5cdb3e64ee2210d6f2a3 | shulme801/Python101 | /UdemyPythonCertCourse/Dunder_Examples.py | 1,017 | 4.3125 | 4 | # https://www.geeksforgeeks.org/customize-your-python-class-with-magic-or-dunder-methods/?ref=rp
# declare our own string class
class String:
# magic method to initiate object
def __init__(self, string):
self.string = string
# print our string object
def __repr__(self):
return 'Object: {}'.format(self.string)
def __add__(self, other):
return self.string + other
# Driver Code
print ("This file's __name__ is %s" %__name__)
if __name__ == '__main__':
# object creation
string1 = String('Hello')
# print object location
print(string1)
#concatenate String object and a string
print(string1 + " world!")
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + " age is " + str(self.age)
def __len__(self):
return len(self.name)
# John = Employee("John Doe", 47)
# print(John)
# print(len(John))
| true |
9bd76fe2cca59bd95d2a5237d8bf34a13ed13c60 | lawtonsclass/s21-code-from-class | /csci1/lec14/initials.py | 742 | 4.21875 | 4 | import turtle # imports the turtle library
import math
turtle.shape("turtle") # make the turtle look like a turtle
turtle.up()
turtle.backward(150)
turtle.right(90)
turtle.down() # put the turtle down so that we can draw again
turtle.forward(200) # draw first line of L
turtle.left(90)
turtle.forward(125)
# space between letters
turtle.up()
turtle.forward(40)
turtle.down()
turtle.left(90)
turtle.forward(200)
# calcuate the weird angle in the N
angle = math.atan(125/200)
angle = math.degrees(angle)
turtle.right(180-angle)
# calculate the weird length for the middle line of the N
length = 125 / math.sin(math.radians(angle))
turtle.forward(length)
turtle.left(180-angle)
turtle.forward(200)
| true |
f14f7efaf33491f9758099e639e1adf4fbc55c50 | lawtonsclass/s21-code-from-class | /csci1/lec19/random_squares.py | 1,136 | 4.21875 | 4 | import turtle
import random
turtle.shape('turtle')
turtle.speed('fastest')
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
i = 1
while i <= 50:
# draw a square with a random side length and a random color
random_index = random.randint(0, len(colors) - 1)
turtle.fillcolor(colors[random_index])
turtle.up() # pick the turtle up
# pick a random starting x & y coordinate
starting_x = random.randint(-300, 300)
starting_y = random.randint(-300, 300)
# move the turtle there
turtle.goto(starting_x, starting_y)
# put the turtle back down
turtle.down()
# pick a random side length for our square
square_side_length = random.randint(50, 200)
# actually draw the square
turtle.begin_fill() # fill in (with the fillcolor) the following shape
turtle.forward(square_side_length)
turtle.left(90)
turtle.forward(square_side_length)
turtle.left(90)
turtle.forward(square_side_length)
turtle.left(90)
turtle.forward(square_side_length)
turtle.end_fill() # I'm done drawing, please fill in my shape Mr. Turtle
i = i + 1 # advance i
| true |
0d613768179d34123018a637a31ce1327587c5fc | lawtonsclass/s21-code-from-class | /csci1/lec30/recursion.py | 961 | 4.1875 | 4 | def fact(n):
# base case
if n == 1:
return 1
else: # recursive case!
x = fact(n - 1) # <-- this is the "recursive call"
# the answer is n * (n-1)!
return n * x
print(fact(5))
def pow(n, m):
if m == 0: # base case
return 1
else: # recursive case
return n * pow(n, m-1)
print(pow(2.5, 5))
def sum_divide_and_conquer(L):
if len(L) == 0: # base case 1
return 0
elif len(L) == 1: # base case 2
return L[0]
else: # recursive case
# first, divide the list L into two halves
midpoint = len(L) // 2
first_half = L[:midpoint]
second_half = L[midpoint:]
# let's recursively "conquer" the two halves!
first_half_sum = sum_divide_and_conquer(first_half)
second_half_sum = sum_divide_and_conquer(second_half)
# final answer is the sum of both halves
return first_half_sum + second_half_sum
print(sum_divide_and_conquer([8, 6, 7, 5, 3, 0, 9, 2]))
| true |
919bc6acd1abd0d772c86c501de1aa4e9395d103 | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/02-Leap-Year/Leap_year.py | 300 | 4.375 | 4 | # purpose - to find leap years of future year from current year
startYear = 2021
print("Enter any future year")
endYear = int(input())
print("List of leap years:")
for year in range(startYear, endYear):
if (0 == year % 4) and (0 != year % 100) or (0 == year % 400):
print(year)
| true |
1407338619c9f08438e00a72f20ee2a1796ffaa2 | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/20-Remove-even-numbers-form-a-list-of-integers/Removing_Even_numbers_in_LIST.py | 419 | 4.1875 | 4 | # purpose- removing even numbers in list
numberList = []
even_numberList = []
n = int(input("Enter the number of elements "))
print("\n")
for i in range(0, n):
print("Enter the element ", i + 1, ":")
item = int(input())
numberList.append(item)
print(" List is ", numberList)
even_numberList = [x for x in numberList if x % 2 != 0]
print("\n")
print("List after removing even numbers\n ", even_numberList)
| true |
31dabba934c1b70d75263ef9bf71549651baa464 | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/03-List-Comprehensions/List_Operations.py | 1,445 | 4.125 | 4 | # purpose - program to perform some list operations
list1 = []
list2 = []
print("Select operation.")
print("1.Check Length of two list's are Equal")
print("2.Check sum of two list's are Equal")
print("3.whether any value occur in both ")
print("4.Display Lists")
while True:
choice = input("Enter any choice ")
if choice in ('1', '2', '3', '4'):
list1Len = int(input("Enter the number of elements in list 1 : "))
for i in range(0, list1Len):
print("Enter the element ", i + 1, ":")
item1 = int(input())
list1.append(item1)
list2Len = int(input("Enter the number of elements in list 2 : "))
for j in range(0, list2Len):
print("Enter the element ", j + 1, ":")
item2 = int(input())
list2.append(item2)
if choice == '1':
if len(list1) == len(list2):
print(" Length are Equal")
else:
print(" Length are Not Equal")
if choice == '2':
if sum(list1) == sum(list2):
print(" Sums are Equal")
else:
print(" Sums are Not Equal")
if choice == '3':
list3 = [x for x in list1 if x in list2]
print("Common elements in both list's are \n", list3)
if choice == '4':
print("List 1 is :\n", list1, " List 2 is :\n", list2)
| true |
7c9d95660844b66ff9becf9f656ed9f16f78ed79 | mengeziml/sorepy | /sorepy/sorting.py | 2,472 | 4.625 | 5 | def bubble_sort(items):
"""Return array of items, sorted in ascending order.
Args:
items (array): list or array-like object containing numerical values.
Returns:
array: sorted in ascending order.
Examples:
>>> bubble_sort([6,2,5,9,1,3])
[1, 2, 3, 5, 6, 9]
"""
n = items.copy()
for i in range(len(n)):
for j in range(len(n)-1-i):
if n[j] > n[j+1]:
n[j], n[j+1] = n[j+1], n[j]
return n
def merge(A, B):
"""Returns a single merged array of two arrays.
Args:
A (array): list or array-like object containing numerical values.
B (array): list or array-like object containing numerical values.
Returns:
array: unsorted.
Examples:
>>> merge([6,2,5],[9,1,3])
[6, 2, 5, 9, 1, 3]
"""
temp_list = []
while len(A) > 0 and len(B) > 0:
if A[0] < B[0]:
temp_list.append(A[0])
A.pop(0)
else:
temp_list.append(B[0])
B.pop(0)
if len(A) == 0:
temp_list = temp_list + B
if len(B) == 0:
temp_list = temp_list + A
return temp_list
def merge_sort(items):
"""Splits array into two sorted equal halves and uses merge(A,B)
to sort items.
Args:
items (array): list or array-like object containing numerical values.
Returns:
array: sorted in ascending order.
Examples:
>>> merge_sort([6,2,5,9,1,3])
[1, 2, 3, 5, 6, 9]
"""
len_i = len(items)
if len_i == 1:
return items
mid_point = int(len_i / 2)
i1 = merge_sort(items[:mid_point])
i2 = merge_sort(items[mid_point:])
return merge(i1, i2)
def quick_sort(items):
"""Return array of items, sorted in ascending order.
Args:
items (array): list or array-like object containing numerical values.
Returns:
array: sorted in ascending order.
Examples:
>>> quick_sort([6,2,5,9,1,3])
[1, 2, 3, 5, 6, 9]
"""
p=items[-1]
l=[]
r=[]
for i in range(len(items)):
if items[i]< p:
l.append(items[i])
if len(l)>1 and len(l)>=len(items)//2:
l=quick_sort(l)
elif items[i]>p:
r.append(items[i])
if len(r)>1 and len(r)>=len(items)//2:
r=quick_sort(r)
items=l+[p]+r
return items
| true |
4663b089240b5f113c3c49e7918204417dff77f7 | BenWarwick-Champion/CodeChallenges | /splitStrings.py | 581 | 4.125 | 4 | # Complete the solution so that it splits the string into pairs of two characters.
# If the string contains an odd number of characters then it should replace
# the missing second character of the final pair with an underscore ('_').
# Example:
# solution('abc') # should return ['ab', 'c_']
# solution('abcdef') # should return ['ab', 'cd', 'ef']
# My Solution
def solution(s):
if (len(s) % 2) != 0:
s += '_'
return [s[i:i+2] for i in range (0, len(s), 2)]
# Best Solution
import re
def solution(s):
return re.findall(".{2}", s + "_") | true |
992ad23ed86e3c42cebb5d4130acaba5dca70eda | ktsmpng/CleverProgrammerProjects | /yo.py | 447 | 4.28125 | 4 | # print from 1 to 100
# if number is divisble by 3 -- fizz
# if number is divisble by 5 -- buzz
# if divisible by both -- fizzbuzz
# 2
# fizz
# 3
def fizzbuzz(start_num, stop_num):
print('_________________')
for number in range(start_num, stop_num + 1):
if number % 3 == 0 and number % 5 == 0:
print("fizzbuzz")
elif number % 3 == 0:
print("fizz")
elif number % 5 == 0:
print("buzz")
else:
print(number)
fizzbuzz(1,300) | true |
661171d9cc55d2b4c5ef7bbfe5c02f9cc5760c43 | Topperz/pygame | /5.first.pygame.py | 2,986 | 4.65625 | 5 | """
Show how to use a sprite backed by a graphic.
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
import time
import math
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
PI = 3.141592653
pygame.init()
# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
# --- Drawing code should go here
# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(WHITE)
pygame.draw.rect(screen, RED, [100, 100, 100, 100])
pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
pygame.draw.line(screen, GREEN, [200, 100], [300, 0], 5)
pygame.draw.line(screen, GREEN, [100, 200], [0, 300], 5)
pygame.draw.line(screen, GREEN, [200, 200], [300, 300], 5)
# Draw on the screen several lines from (0,10) to (100,110)
# 5 pixels wide using a for loop
for y_offset in range(0, 100, 10):
pygame.draw.line(screen,RED,[0,10+y_offset],[100,110+y_offset],5)
#pygame.display.flip()
#time.sleep(1)
#for i in range(200):
#
# radians_x = i / 20
# radians_y = i / 6
#
# x = int( 75 * math.sin(radians_x)) + 200
# y = int( 75 * math.cos(radians_y)) + 200
#
# pygame.draw.line(screen, BLACK, [x,y], [x+5,y], 5)
#pygame.display.flip()
#time.sleep(0.1)
# Draw an arc as part of an ellipse. Use radians to determine what
# angle to draw.
#pygame.draw.arc(screen, GREEN, [100,100,250,200], PI, PI/2, 2)
#pygame.draw.arc(screen, BLACK, [100,100,250,200], 0, PI/2, 2)
#pygame.draw.arc(screen, RED, [100,100,250,200],3*PI/2, 2*PI, 2)
#pygame.draw.arc(screen, BLUE, [100,100,250,200], PI, 3*PI/2, 2)
pygame.draw.arc(screen, BLACK, [20, 220, 250, 200], 0, PI/2, 2)
pygame.draw.arc(screen, GREEN, [20, 220, 250, 200], PI/2 , PI, 2)
pygame.draw.arc(screen, BLUE, [20, 220, 250, 200], PI, PI * 1.5, 2)
pygame.draw.arc(screen, RED, [20, 220, 250, 200], PI * 1.5 , PI * 2, 2)
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()
| true |
9bb66c9e7dbbbdcc24a02c399aa13c3676038941 | Bardoctorus/General-Bumtastic-Silly | /Bumdamentals/fizzbuzz.py | 362 | 4.28125 | 4 | """ any number divisible by three is replaced by the
word fizz and any divisible by five by the word buzz.
Numbers divisible by both become fizz buzz.
"""
for i in range(1, 100):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i) | false |
39984a91ad8bc8209dca055467c40ad7560a898e | applecool/Python-exercises | /key_value.py | 594 | 4.125 | 4 | # Write a function that reads the words in words.txt and stores
# them as keys in a dictionary. It doesn't matter what the values
# are.
#
# I used the python's in-built function random to generate random values
# One can use uuid to generate random strings which can also be used to
# pair the keys i.e., in this case the words in the .txt file
import random
output = dict() #creates an empty dictionary
words = open('words.txt')
line = words.readline()
def key_value():
for line in words:
word = line.strip()
output[word] = random.random()
return output
print key_value()
| true |
18460b5647f2e3b58d59e9d57410cc81cdcf60c7 | cherrymar/google_cssi | /CSSI-Files/Example_Python/Day1/lesson1.py | 679 | 4.25 | 4 | """
print( "Hello World" )
#I can write a comment after this pound sign
print( "bye bye" )
#variables
name = "Cher Ma"
print( "hi there: " )
print( name )
#user input
user = raw_input("What's your name? " )
print( "Hi " + user )
num1 = int( raw_input( "Enter a number: " ) )
num2 = int( raw_input( "Enter another number: " ) )
total = num1 + num2
print( total )
"""
x = str(int("2"))
print x + str(1)
userYear = raw_input( "What year were you born in? " )
age = 2018 - int( userYear )
print( "You are " + str( age ) + " years old this year." )
userAge = raw_input( "How old are you this year? " )
year = 2018 - int( userAge )
print( "You were born in " + str( year ) )
| false |
3cf19e42662c084e91194204929d362112f3e98c | singerdo/songers | /第一阶段/课上实例练习/day02/demo05.py | 582 | 4.34375 | 4 | """
类型转换
结果 = 类型名称(待转换数据)
练习:exercise04.py
"""
# 字符串 --> 整数
'''str_number = "250"
int_number = int(str_number)
print(type(int_number))
# 注意:待转换数据必须"长得像"代转类型
# print(int("250+"))# 250+ 不像 整数,所以报错(第三门课程解决)
# print(int("1.23"))
# 小数 --> 整数'''
print(int(8.93)) # 8
# ? --> 字符串
print(str(100.444))
# 四舍五入保留指定精度
# 结果 = round(需要计算的小数,精度)
print(round(1.29, 3)) # 1.3
print(round(1.21, 2)) # 1.2
| false |
d3210816dac9893a01061a6687f17b13304c3289 | subreena10/dictinoary | /existnotexistdict.py | 249 | 4.46875 | 4 | dict={"name":"Rajiu","marks":56} # program to print 'exist' if the entered key already exist and print 'not exist' if entered key is not already exists.
user=input("Enter ur name: ")
if user in dict:
print("exist")
else:
print("not exists") | true |
090de8d31c4ea6ce5b30220d8e3f7679d8328db3 | adreher1/Assignment-1 | /Assignment 1.py | 1,418 | 4.125 | 4 | '''
Rose Williams
rosew@binghamton.edu
Section #B1
Assignment #1
Ava Dreher
'''
'''
ANALYSIS
RESTATEMENT:
Ask a user how many people are in a room and output the total number of
introductions if each person introduces themselves to every other person
once
OUTPUT to monitor:
introductions (int) - when each person introduces themselves to every other
person once
INPUT from keyboard:
person_count (int)
GIVEN:
HALF (int) - 2
FORMULA:
(person_count * (person_count - 1)) / HALF
'''
# CONSTANTS
HALF = 2
# This program outputs the total number of introductions possible if each
# person in a room introduces themselves to every other person in the room
# once, given the number of people in the room
def main():
# Explain purpose of program to user
print("How many introductions will occur if everyone " + "\n" + "introduces themseves to every other person?")
# Ask user for number of people in room
person_count_str= input('number of people in room:')
# Convert str data to int
person_count = int(person_count_str)
# Use the formula to compute the result
introductions = (person_count * (person_count - 1)) / HALF
introductions = str(introductions)
# Display labeled and formatted introduction count
print('There are '+ introductions + ' introductions')
if __name__ == '__main__':
main()
| true |
29a9472bf05258a090423ef24cc0c64311a6272b | acc-cosc-1336/cosc-1336-spring-2018-Miguelh1997 | /src/midterm/main_exam.py | 561 | 4.40625 | 4 | #write import statement for reverse string function
from exam import reverse_string
'''
10 points
Write a main function to ....
Loop as long as user types y.
Prompt user for a string (assume user will always give you good data).
Pass the string to the reverse string function and display the reversed string
'''
def main():
n = 'Y'
while n == 'Y':
string1 = input('Please input a string: ')
new = reverse_string(string1)
print(new)
n = input("Press 'y' to enter another string... ")
n = n.upper()
| true |
f16f06d76cb51cff2e10bc64d9310890e041231b | abalidoth/dsp | /python/q8_parsing.py | 673 | 4.3125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import pandas as pd
footy = pd.read_csv(football.csv)
footy["Diff"]=[abs(x-y) for x,y in zip(footy.Goals, footy["Goals Allowed"])]
whichsmallest = footy.Diff[footy.Diff==min(footy.Diff)].index[0]
print(footy.Team[whichsmallest])
| true |
645e285a751310786073fefba08294bf7850b051 | 40309/variables | /assignment_improvement_exercise_py.py | 402 | 4.28125 | 4 | #john bain
#variable improvement exercise
#05-09-12
import math
radius = float(input("Please enter the radius of the circle: "))
circumference = int(2* math.pi * radius)
circumference = round(circumference,2)
area = math.pi * radius**2
area = round(area,2)
print("The circumference of this circle is {0}.".format(circumference))
print("The area of this circle is {0}.".format(area))
| true |
73760296f75889f8eaba190a9bc38c2d03555c95 | 40309/variables | /Development Exercise 3.py | 342 | 4.1875 | 4 | #Tony K.
#16/09/2014
#Development Exercise 3
height = float(input("Please enter your height in inches: "))
weight = float(input("Please enter your height in stones: "))
centimeter = height* 2.54
kilogramm = weight * (1/0.157473)
print("You are {0} cenimeters tall and you weigh {1} kilogramm".format(centimeter,kilogramm))
| true |
5df0fb2d35b5bda4776c288f974e6327a39ea9f7 | trepudox/Python | /UNIP/exerc fac/exe11.py | 882 | 4.25 | 4 | #Escreva um programa que leia números inteiros. O programa deve ler até que o usuário digite 0. No final da execução
#exiba a quantidade de numeros digitados assim como a soma e a media aritmética
x = 1
contador = 0
soma = 0
media = 0
while True:
if x == 0:
break
x = int(input('Digite um número, caso queira encerrar o programa digite 0: '))
contador += 1
soma += x
print(x)
contador -= 1
if contador <= 0:
print('A quantidade de números digitados foi de: 1\nA soma de todos os números foi de: {}\nA média de todos os '
'números é de: {:.2f}\nFim do programa.'.format(soma, media))
else:
media = soma / contador
print('A quantidade de números digitados foi de: {}\nA soma de todos os números foi de: {}\nA média de todos os '
'números é de: {:.2f}\nFim do programa.'.format(contador, soma, media))
| false |
29cdd670a2f1da4fed0120f2522b7b5a7820a807 | fredo1712/github-tricks | /helloworld.py | 650 | 4.15625 | 4 | ##my_string = "Hello World"
##print(my_string)
##
##var1 = "Allo \"Haiti est un pays de merde\" a dit Trump"
##print(var1)
##
##
##name = 'Phanou'
##greeting = f'Hello, {name}'
##
##print(greeting)
##your_name = input("Please enter your name: ")
##print (f'Hello, {your_name}')
##
##age = int(input("Please enter your age: "))
##print (f'you have lived for {age * 12} month')
##name = input ("Please enter your name: ")
##print("Hello, " + name)
##
##age = int(input("Please enter your age: "))
##print (age * 12)
age = 34
is_over_age = age >= 30
is_under_age = age < 30
is_age = age == 34
print (is_over_age)
print (is_under_age)
print (is_age)
| false |
f88400c71dc8f6a5a8298f4ad5861eda45f73a86 | Goryaschenko/Python_GeekBrain_HW | /Lesson_1/Max number.py | 667 | 4.21875 | 4 | """
Задание 3:
Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.
"""
n = input("Введите целое положительное число ")
n_len = len(n)
i = 1
max_n = n[0]
while i < n_len:
if n[i] > max_n:
max_n = n[i]
i += 1
print("Максимум = ", max_n)
#Максимум находит но как сделать только арифметическими операциями не понял.....
#Any text | false |
3d1233434f7736cdc299f39fb440fafa3416d5a9 | Goryaschenko/Python_GeekBrain_HW | /lesson_5/5_sum_from_file.py | 1,702 | 4.125 | 4 | """
Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
"""
# Вы можете вводить числа и буквы не боясь что буквы попадут в список
with open("5_sum_from_file.txt", "w", encoding='utf-8') as f:
value = input("Введи несколько чисел через пробел: ")
num_list = []
num = ''
sum = 0
#### УБИРАЕМ БУКВЫ ИЗ СТРОКИ И ОСТАВЛЯЕМ ЧИСЛА ####
for char in value:
if char.isdigit(): # если символ число
num = num + char # записываем его в num
else:
if num != '': # если num не пустой
num_list.append(int(num)) # преобразуем num в число и добавлем в список
num = '' # опусташаем num
if num != '': # проверяем конец строки
num_list.append(int(num))
result = ' '.join(str(el) for el in num_list) # Преобразуем список в строку
print(f"Ваши числа: {result}")
f.write(result)
#### ОТКРЫВАЕМ ФАЙЛ ДЛЯ ПОДСЧЕТА ЗНАЧЕНИЙ ИЗ НЕГО #####
with open("5_sum_from_file.txt", "r", encoding='utf-8') as f:
data = f.read().split()
sum = 0
for el in data:
sum += int(el)
print(f"Сумма чисел в файле = {sum}") | false |
b88bc6f0378938dc46e56f26fc80331a8dc91364 | Goryaschenko/Python_GeekBrain_HW | /lesson_3/2_phonebook.py | 1,237 | 4.1875 | 4 | """
Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
имя, фамилия, год рождения, город проживания, email, телефон.
Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой.
"""
def phonebook(name, surname, birthday, citi, email, phone):
my_dict = dict(name=name, surname=surname, birthday=birthday, citi=citi, email=email, phone=phone)
list = []
for key in my_dict.keys():
list.append(my_dict.get(key))
return " ".join(list)
print("Введите через пробел ваши: \n имя, фамилия, год рождения, город проживания, email, телефон")
name, surname, birthday, citi, email, phone = (str(i) for i in input().split())
print(f"Вы ввели следующие данные: {phonebook(name=name, surname=surname, birthday=birthday, citi=citi, email=email, phone=phone)}")
# иван горященко 31.10.1990 москва gor@ 8926
| false |
5e20c1fde5e1ebd93f22d718ac78f699f31a387c | lloydieG1/Booking-Manager-TKinter | /data.py | 1,013 | 4.1875 | 4 | import sqlite3
from sqlite3 import Error
def CreateConnection(db_file):
''' create a database connection to a SQLite database and check for errors
:param db_file: database file
:return: Connection object or None
'''
#Conn starts as 'None' so that if connection fails, 'None' is returned
conn = None
try:
#attempts to connect to given database
conn = sqlite3.connect(db_file)
#prints version if connection is successful
print("Connection Successful\nSQL Version =", sqlite3.version)
except Error as e:
#prints the error if one occurs
print("Error1 = " + str(e))
return conn
def get():
db = "test.db"
conn = CreateConnection(db)
if conn == None:
print('Connection failed')
#SQL command to insert data
sql = '''SELECT * FROM bookings_table;'''
#Creates cursor
c = conn.cursor()
#Executes SQL command using user input
results = c.execute(sql).fetchall()
return results | true |
f5c41d06bb1137f0d1aac5b0f1dbedc9604cc91b | NickNganga/pyhtontake2 | /task3.py | 547 | 4.125 | 4 | def list_ends(a_list):
return (a_list[0], a_list[len(a_list)-1])
# number of elements
num = int(input("Enter number of elements : "))
# Below line read inputs from user using map() function
put = list(map(int,input("\nEnter the numbers : ").strip().split()))[:num]
# Below Line calls the function created above.
put1 = list_ends(put)
#Outputs the values under indices '0' & '-1' (the last one in the list).
print("\nList is - ", put)
#Outputs the values under indices '0' & '-1' (the last one in the list).
print("\nNew List is - ", put1) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.