blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
46bfc56df269fa617b037f8c3236e981b2de505b | droogadulce/HackerRank | /math/maximum_draws.py | 1,324 | 4.125 | 4 | #!/bin/python3
"""
Maximum Draws
Problem: Jim is off to a party and is searching for a matching pair of socks. His drawer is
filled with socks, each pair of a different color. In its worst case scenario, how many socks (x)
should Jim remove from his drawer until he finds a matching pair?
Input Format
The first line contains the number of test cases T.
Next T lines contains an integer N which indicates the total pairs of socks present in the drawer.
Output Format
Print the number of Draws (x) Jim makes in the worst case scenario.
Constraints
1 <= T <= 1000
0 < N < 10e6
Sample Input
2
1
2
Sample Output
2
3
Explanation
Case 1: A pair of socks are present, hence exactly 2 draws for the socks to match.
Case 2: 2 pair of socks are present in the drawer. The first and the second draw might result
in 2 socks of different color. The 3rd sock picked will definitely match one of previously
picked socks. Hence, 3.
"""
import os
import sys
#
# Complete the maximumDraws function below.
#
def maximumDraws(n):
#
# Write your code here.
#
return n + 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
fptr.write(str(result) + '\n')
fptr.close() | true |
dc987a724bf011bc654ab24a7a8674ec4700659d | raunakchowdhury/softdevhw2 | /20_anon-reduce/listcomp.py | 1,051 | 4.15625 | 4 | from functools import reduce
f = open('pride_and_prejudice.txt', 'r').read().split('\n')
lines = [set(x.split(' ')) for x in f]
def find_freq(word):
"""find the freq of one word"""
word_list = [1 for line in lines if word in line] # create a list of 1s that reduce() can use
return reduce(lambda x,y: x+1 if y==1 else x, word_list) # x takes on the type of the elements in the array
def find_freq_words(words):
"""finds freq of a list of words and returns their total"""
word_list = [1 for line in f if words in line]
return reduce(lambda x,y: x+1 if y==1 else x, word_list) # x takes on the type of the elements in the array
def find_largest_freq():
"""find the freq of the word that occurs the most."""
words_list = {word for line in lines for word in line}
word_freqs = [(find_freq(word), word) for word in words_list]
max_freq = max(word_freqs)
return max_freq[0], max_freq[1]
if __name__ == '__main__':
print(find_freq('be'))
print(find_freq_words('Jane Austen'))
print(find_largest_freq())
| true |
79a6347e6162206f0950abf21ca33f9f1e795862 | machil1/CPS-3320 | /Scrabble.py | 1,543 | 4.25 | 4 | #Lawrence Machi III
#Make a scrabble game using if statements and functions
#Use if statements to check for a letter inputted by user and return a score
def letterScore(letter):
if letter in ' a n o e r s t u i l ':
return 1
if letter in ' d g ':
return 2
if letter in ' b c m p ':
return 3
if letter in ' f h v w ':
return 4
if letter in ' k ':
return 5
if letter in ' j x ':
return 8
if letter in ' q z ':
return 10
else:
return 0
#Using the letterScore function traverse through the word inputted by user
#and check each letter and return a score for the entire word
def wordScore(word):
score = 0
for current in word:
score += letterScore(current)
return score
#Implemented a total score
def main():
totalScore = 0
letter = input("Enter a letter ").lower()
print("Your score is:" , letterScore(letter))
while True:
#Use .lower() to compensate for any case characters
word = input("Enter a word ").lower()
print("Your score is:" ,wordScore(word))
#Below add the total score
totalScore += wordScore(word)
#Use continue to keep playing the game and accumulate a total score
userInp = input("If you want to continue type yes if not type no. ").lower()
if(userInp == "yes"):
continue
elif(userInp == "no"):
print("Your total score is:", totalScore)
return False
else:
return False
main()
| true |
003e03220e2193fe7147dbbea0016eb61fb98283 | wolfdigit/interview-mygo | /main.py | 735 | 4.125 | 4 | """
Please use Python 3 to answer question
Welcome to answer with unit testing code if you can
After you finish coding, please push to your GitHub account and share the link with us.
"""
# Please write a function to reverse the following nested input value into output value
# Input:
input_value = {
'hired': {
'be': {
'to': {
'deserve': 'I'
}
}
}
}
# Output:
output_value = {
'I': {
'deserve': {
'to': {
'be': 'hired'
}
}
}
}
def main():
from Solve import Solve
#output = Solve.solve(input_value)
#print(output)
from Test import Test
Test.runAll(Solve.solve)
if __name__ == '__main__':
main() | true |
ff7e6cb682c8d1533dc7b1b4868286db53c5c633 | bj730612/Bigdata | /01_Jump_to_Python/Chapter03/119_3.py | 315 | 4.125 | 4 | A=True
B=False
if A==False and B==False:
print(" A==False and B==False ̿ Ǵ ɹ")
if A and B == False:
print(""" A==False and B==False ̿ ϴ ǵ A
° Trueε print DZ ǽ ߸ۼǾ""")
| false |
fbb859c51e135ac84a2d763a90b2208a810ecadd | gergelynagyvari/euler | /src/p024-lexicographic-permutation.py | 1,462 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
# 012 021 102 120 201 210
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
import math
def main():
count = 10
target = 999999
digits = [x for x in range(count)]
permutations = { x: math.factorial(x) for x in range(count)}
solution = []
print(digits)
print(permutations)
covered = 0
for i in reversed(range(count)):
print('\n------- Checking possible permutations with {} items -------'.format(i))
print('{} permutations covered with array: {}, remaining: {}'.format(covered, repr(solution), repr(digits)))
index = (target - covered) / permutations[i]
print('there are {} items that use use {} permutations, total={}'.format(index, permutations[i], index * permutations[i]))
covered += index * permutations[i]
print('total covered solutions so far is {}'.format(covered))
solution.append(digits.pop(index))
print('"{}" is moved from digits to solution solution: {}, digits: {}'.format(solution[-1], repr(solution), repr(digits)))
if __name__ == '__main__':
main()
| true |
14c34e0c8224c06271563e594c741caca8ea9b0c | Khailas12/REST-API-using-Flask | /Basic_try/my_module/model/transaction_type.py | 506 | 4.1875 | 4 | from enum import Enum
class TransactionType(Enum):
INCOME = "INCOME"
EXPENSE = "EXPENSE"
# It's a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The enums are evaluatable string representation of an object also called repr(). The name of the enum is displayed using 'name' keyword. Using type() we can check the enum types
# Eg: Compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week | true |
c7d59b7969f9ab48db831d065036aea329e9c727 | nhadley1/Python-Exercises | /dict_sort.py | 657 | 4.21875 | 4 |
# Sorts strings by length, prints length, string
def sortLen(dictionary):
sort_dic = sorted(dictionary.items(), key=lambda key: key[1])
for i in sort_dic:
print(i[1], i[0])
#Set up empty dictionary that will be filled with user input.
dic = {}
#Allows user to input string
while True:
string = input('Enter String: ')
#Sets string length.
dic[string] = len(string)
another = input('Enter another? (y/n): ')
#Doesn't account for any other string being input,
#anything other than 'y' will break out of loop.
if another == 'y':
continue
else:
break
#Print sorted dictionary.
sortLen(dic) | true |
4d7bedcdcc6b862d110df5bab889652a5d52fdc6 | MarianMykolaichuk/h_tsk | /10.06.19/no_yelling.py | 547 | 4.125 | 4 | # #Write a function taking in a string like WOW this is REALLY
# amazing and returning Wow this is really amazing.
# String should be capitalized and properly spaced. Using re and string is not allowed.
# Examples:
# filter_words('HELLO CAN YOU HEAR ME') #=> Hello can you hear me
# filter_words('now THIS is REALLY interesting') #=> Now this is really interesting
# filter_words('THAT was EXTRAORDINARY!') #=> That was extraordinary!
def filter_words(st):
st = st.lower()
return " ".join((st[0].upper() + st[1:]).split()) | true |
bae2cdab201421ae0258899a555a889f8b0b07bd | gerardoalfredo2/Data-Structures-and-algoritms | /Algoritms python book/Chapter 7/lliststack.py | 1,208 | 4.28125 | 4 | # Implementation of the Stack ADT using a singly linked list.
class Stack:
#Creates an empty stack
def __init__(self):
self._top=None
self._size=0
#Returns true if the stack is empty or False
def isEmpty(self):
return self._top is None
#Returns the number of item in the stack
def __len__(self):
return self._size
# Returns the top item on the stack without removing it.
def peek( self ):
assert not self.isEmpty(), "Cannot peek at an empty stack"
return self. _top.item
# Removes and returns the top item on the stack.
def pop(self):
assert not self.isEmpty(),"Cannot pop from an empty stack"
node=self._top
self._top=self._top.next
self._size-=1
return node.item
#Pushes an item onto the top of the stack.
def push(self,item):
self._top=_StackNode(item,self._top)
self._size+=1
#The private storage class for creating stack nodes.
class _StackNode:
def __init__(self, item,link):
self.item=item
self.next=link
new_list=Stack()
#print(new_list._size)
new_list.push(3)
new_list.push(4)
print(new_list.pop())
| true |
a913f4252537812d12bdafb7e3c5370db7393f84 | gerardoalfredo2/Data-Structures-and-algoritms | /Algoritms python book/Chapter 5/Search.py | 1,756 | 4.1875 | 4 | import random
def linearSearch(theValues, target):
n=len(theValues)
i=0
for i in range(n):
#If the target is in the ith element, return True
if theValues[i]==target:
return True,i
i=i+1
return False,i
def sortedLinearSearch(theValues,item):
n=len(theValues)
j=0
for i in range(n):
#if the target is found in the ith element,return True
if theValues[i]==item:
return True,j
#if the target is arger than the ith, its not in the list
elif theValues[i]>item:
return False,j
j=j+1
return False,j
def binarySearch(theValues,target):
#Start with the entire sequence of elements for a ordered list
low=0
high=len(theValues)-1
i=0
#reapeatedly subdivide the sequence in half until the target is found.
while low<=high:
#find the midpoint of the sequence.
mid=(high+low)//2
#does the midpoint contains target
if theValues[mid]==target:
return True,i
#or does the target precede the midpoint?
elif target<theValues[mid]:
high=mid-1
#or does it follow the midpoint?
else:
low=mid+1
i=i+1
#if the sequence cannot be subdivided further, we're done.
return False,i
items=list(range(0,10000))
#random.shuffle(items)
items2=list(range(0,1000))
#random.shuffle(items2)
items3=list(range(0,100))
#random.shuffle(items3)
unit_test=[items,items2,items3]
for i in unit_test:
print("linearsearch for ",len(i)//2,linearSearch(i,len(i)//2))
print("sortedLinearSearch for",len(i)//2,sortedLinearSearch(i,len(i)//2))
print("binarySearch for ",len(i)//2 ,(binarySearch(i,len(i)//2)))
| true |
f9296e699ef6d04048e06d05531237b43fb978e0 | gerardoalfredo2/Data-Structures-and-algoritms | /Algoritms python book/Chapter 6/SingleLinkedList.py | 2,333 | 4.15625 | 4 | #Construct a node
class ListNode:
def __init__(self,data):
self.data=data
self.next=None
#Create an empty linked list or with elements if a list is provided
class LinkedList:
def __init__(self,listElements=None):
self.__head=None
self.__tail=None
self.size=0
if(listElements!=None):
for i in listElements:
self.addTobeg(i)
#Add a new element to the beggining of the linked list
def addTobeg(self,data):
new_node=ListNode(data)
if self.__head==None:
self.__tail=new_node
new_node.next=self.__head
self.__head=new_node
self.size+=1
#Add a new element to the end of the linked list
def addToTail(self,data):
new_node=ListNode(data)
if self.__head== None:
self.addTobeg(data)
else:
self.__tail.next=new_node
self.__tail=new_node
self.size+=1
def testing(self):
print(self.__head.next.next.next)
def remove(self,data):
predNode=None
curNode=self.__head
while curNode is not None and curNode.data!=data:
predNode=curNode
curNode=curNode.next
assert curNode is not None,"data is not in the linked list"
self.size-=1
if curNode is self.__head:
self.__head=curNode.next
else:
predNode.next=curNode.next
return curNode.data
def search(self,data):
curNode=self.__head
while curNode is not None and curNode.data != data:
curNode=curNode.next
return curNode is not None
"""Run in all elements of the linked list"""
def traversal(self):
curNode=self.__head
while curNode is not None:
print (curNode.data)
curNode=curNode.next
#myListElements=[3,1,2,3,4,5]
#myList=LinkedList(myListElements)
#myList.addTobeg(1)
#myList.addTobeg(2)
#myList.traversal()
#myList.addToTail(8)
#myList.addTobeg(1)
#myList.addTobeg(4)
#myList.addToTail(1)
#myList.remove(5)
#myList.traversal()
#print("Size of %d element"%(myList.size))
#print("is the element 8 in the linked list: ",(myList.search(8)))
myListElements=[3,1,2,3,4,5]
myList2=LinkedList(myListElements)
print(myList2.testing())
| true |
43200a82afa1b359fe5864200dd4bbf40348261d | nnim99/Introduction-to-Programming-Python- | /Lab1/task3.py | 223 | 4.1875 | 4 | def func():
radius=input ("Enter radius of the circle:")
value= int(radius)
print (value)
#value of pie is 3.14 and formula for circumference is 2pie r^2
Circumference= 2 * 3.14 * (value)
print (Circumference)
func() | true |
4013c8374fefafb1e578e1ccd6f9d3f253efb44f | lobhaum/python | /cursoemvideo/aulas/aula09.py | 1,330 | 4.34375 | 4 | frase = 'Curso em Vídeo Python'
print(frase)
print('A quarta letra é:',frase[3])
print('Da quarta letra até a 12a:', frase[3:13])
print('Do inicio até a 12a:', frase[:13])
print('Da 12a até o final:', frase[13:])
print('Da 2a letra até a 14a letra pulando de dois em dois:',frase[1:15:2])
print('Dentro da frase: Curso em Vídeo Python existe :',frase.count('o'),' letra o')
print(frase.upper())
print('O tamanho da frase é: ',len(frase))
print(frase.replace('Python', 'Android'))
print(frase)
frase = frase.replace('Python', 'Android')
print(frase)
print('Curso' in frase)
print(frase.find('Curso'))
print(frase.lower().find('vídeo'))
print(frase.split())
dividido = frase.split()
print(dividido)
print(dividido[0])
print(dividido[2][3])
print("""Resumo Indicativo: resume somente os fatos importantes, as principais ideias, sem que haja exemplos oferecidos do texto original. É o tipo de resumo mais pedido nas escolas.
Resumo Informativo: resume as informações e/ou dados qualitativos e quantitativos expressos no texto original. Se confunde com os fichamentos e geralmente são utilizado em textos acadêmicos.
Resumo Crítico: chamado de resenha crítica, ele resume as informações do texto original os quais são acrescentados juízos de valor, ou seja, surge argumentos do autor e do escritor do resumo.""")
| false |
73b31f3a40da0cd938d7e54f56a2f8108300020d | madboy/advent_2016 | /day3_part1.py | 412 | 4.28125 | 4 | """
Which are possible triangles?
In a valid triangle, the sum of any two sides must be larger than the remaining side.
"""
import fileinput
def valid_triangle(triangle):
sides = list(map(int, triangle.split()))
sides.sort()
return (sides[0]+sides[1]) > sides[2]
count = 0
for line in fileinput.input():
triangle = line.strip()
if valid_triangle(triangle):
count += 1
print(count)
| true |
00dea7b67b36298f1d5a92992c06d8744dedcb63 | Anishadahal/Assignmen2_tIW | /Functions/q12.py | 489 | 4.28125 | 4 | # 12. Write a Python program to create a function that takes one argument, and
# that argument will be multiplied with an unknown given number.
def func_compute(n):
return lambda x: x * n
result = func_compute(2)
print("Double the number of 15 =", result(15))
result = func_compute(3)
print("Triple the number of 15 =", result(15))
result = func_compute(4)
print("Quadruple the number of 15 =", result(15))
result = func_compute(5)
print("Quintuple the number 15 =", result(15))
| true |
2702013616da5cac0b349c984ceae2d60b491588 | Anishadahal/Assignmen2_tIW | /DataTypes/q13.py | 384 | 4.28125 | 4 | # 13. Write a Python program that accepts a comma separated sequence of words
# as input and prints the unique words in sorted form (alphanumerically)
def sort_words():
items = input("Input comma separated sequence of words \n")
words = items.split(",")
result = "\n".join(sorted(list(set(words))))
print("Unique and sorted: \n")
print(result)
sort_words()
| true |
7caf6ceaa11162c40ab76f2f787b21ed7fb23d9c | Anishadahal/Assignmen2_tIW | /DataTypes/q39.py | 204 | 4.53125 | 5 | # 39. Write a Python program to unpack a tuple in several variables.
# create a tuple
tuple_x = 4, 8, 3
print(tuple_x)
n1, n2, n3 = tuple_x
# unpack a tuple in variables
print(n1)
print(n2)
print(n3)
| true |
6fb47f0a912ba5c0fc83d40daa8b67bdfd80e8a4 | Anishadahal/Assignmen2_tIW | /DataTypes/q18.py | 375 | 4.40625 | 4 | # 18. Write a Python program to get the largest number from a list.
def largest_number():
list1 = [int(item) for item in (input("Enter the numbers in a comma separated sequence\n").split(","))]
print(list1)
largest = 0
for num in list1:
if num > largest:
largest = num
return largest
print("Largest Number = ", largest_number()) | true |
97b07e9716503339b6ae78a2ad8df9be418abde0 | Anishadahal/Assignmen2_tIW | /DataTypes/q4.py | 400 | 4.15625 | 4 | #4. Write a Python program to get a single string from two given strings, separated
# by a space and swap the first two characters of each string.
# Sample String : 'abc', 'xyz'
# Expected Result : 'xyc abz'
def join_strings():
text1 = input("Enter first string\n")
text2 = input("Enter second string\n")
return text1 + " "+ text2
# print(join_strings())
r = join_strings()
print(r) | true |
fb661316f836202da715b6bf44fcf4b280503725 | aswinsajikumar/Python-Programs | /Roots of Quadratic Equation.py | 468 | 4.1875 | 4 | import math
print ('General form of a quadratic equation is ax²+bx+c')
a=int(input('Enter coefficient of x²:'))
b=int(input('Enter coefficient of x:'))
c=int(input('Enter constant:'))
D=(b*b)-(4*a*c)
if D==0:
x=-b/(2*a)
print (x)
print ('Roots are equal')
elif D>0:
x1=(-b+math.sqrt(D))/(2*a)
x2=(-b-math.sqrt(D))/(2*a)
print ('x1=',x1,'& x2=',x2)
print ('Roots are real')
else:
print ('Roots are imaginary')
| true |
3d4940e7e9bbd6d51526070ee84a4bc9f1b409a8 | bhnybrohn/Research-Assistant---Crypto-Decentralization- | /Research Assitant Solution/Computer Science Solutions/Tolu Smith Proth Number Python.py | 1,254 | 4.3125 | 4 | #QUESTION
# Write a function that takes in a Proth Number and uses
# Proth's theorem to determine if said number is prime?
#ANSWER
# Given a positive integer n, check if it is a Proth number.
# If the given number is a Proth number then print ‘Yes!’ else print ‘No!’.
# Proth Number, In mathematics,is a positive integer of the form n = k * 2n + 1
# where k is an odd positive integer and n is a positive integer such that 2n > k .
#SOLUTION
def isPowerOfTwo(n): #Check The Power Of Two
return (n and (not(n & (n - 1))))
def isProthNumber( n): # Check If The Given Number Is Proth Number Or Not
k = 1
while(k < (n//k)): # check if k divides n or not
if(n % k == 0): # Check if n / k is power of 2 or not
if(isPowerOfTwo(n//k)):
return True
# update k to next odd number
k = k + 2
return False
# Get The Value For n
while True:
print("Press 0 to end Program");
n = int(input("Input a number to check for Proth's Validity: "));
if(n == int("0")):
print("Program Closed")
break;
if(isProthNumber(n-1)):
print("Yes!, {} is a Proth Number".format(n));
else: print("No!,{} is not a Proth Number".format(n));
| true |
52eefd2b32944abb404dcdcff7c7afc0e67b960a | fedorovmark111/homework_9fm | /bin_basic.py | 580 | 4.125 | 4 | import typing as tp
def find_value(nums: tp.Sequence[int], value: int) -> bool:
"""
Find value in sorted sequence
:param nums: sequence of integers. Could be empty
:param value: integer to find
:return: True if value exists, False otherwise
"""
left,right=0,len(nums)
if not nums:
return False
while left<right:
mid=(left+right)//2
if nums[mid]<value:
left=mid+1
elif nums[mid]>value:
right=mid
else:
return True
return left<len(nums) and nums[left]==value
| true |
92bbe182dd8179cf4156c54ff271c452b53bbc73 | herolibra/PyCodeComplete | /Others/Builtin/generator/zrange.py | 702 | 4.125 | 4 | # coding=utf-8
"""
在Python中,使用生成器可以很方便的支持迭代器协议。
生成器通过生成器函数产生,生成器函数可以通过常规的def语句来定义,
但是不用return返回,而是用yield一次返回一个结果,
在每个结果之间挂起和继续它们的状态,来自动实现迭代协议。
"""
def Zrange(n):
print "begining of Zrange"
i = 0
while i < n:
print "before yield", i
yield i
i += 1
print "after yield", i
print "endding fo Zrange"
zrange = Zrange(3)
print "---------"
print zrange.next()
print "---------"
print zrange.next()
print "---------"
print zrange.next()
print "---------"
| false |
ccff11cbba17779a1c7874a24449a90fb5eefe2c | liamw309/PyEncrypt | /keycreater.py | 1,099 | 4.28125 | 4 | import random
class keycreater(object):
'''
This class is used to create a key for the encryption
'''
def __init__(self):
'''
This method helps to create the key. It creates a whole new key by appending a new list (key) and removing it from the old list (alphabet). It does this in a random order.
Attributes: alphabet (base list), key (new list), char (random letter/number from alphabet)
'''
alphabet = ['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', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'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', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '[', '{', ']', '}', '|', ':', ';', '<', '>']
self.key = []
while len(self.key) < 35:
char = random.choice(alphabet)
alphabet.remove(char)
self.key.append(char)
def createkey(self):
return self.key | true |
0e31b4c944773a719dce21101fc90de1233c0bb0 | RicardsGraudins/Python-Fundamentals | /Solutions/05_guessing_game.py | 1,441 | 4.15625 | 4 | #Importing random library https://docs.python.org/3/library/random.html
import random
#Answer variable is a random int between 0-10 and can also be either 0 or 10
answer = random.randint(0,10)
correctGuess = False
tries = 0
prevGuess = None
#The while loop runs endlessly until the user inputs the correct answer
while(correctGuess is False):
#If the user enters invalid input, inform the user of the exception https://docs.python.org/2/tutorial/errors.html
try:
guess = int(input("Guess the number: "))
print("You entered %d" % guess)
#If the user guesses correctly, add 1 to tries and set correctGuess to True which exits the while loop
if (guess == answer):
print("You guessed correct, the number is %d!" % guess)
tries = tries + 1
print("It took you %d tries." % tries)
correctGuess = True;
#Else, if the user answers incorrectly:
#Add 1 to tries if the previous guess wasn't the same number, in other words,
#if the user enters the same guess n number of times consecutively, it will only count as 1 try
else:
print("You guessed incorrectly, try again!")
if(prevGuess != guess):
tries = tries + 1
prevGuess = guess
#If the guess is lower or higher than the answer, give the user a hint
if (guess < answer):
print("Your guess is too low.")
elif (guess > answer):
print("Your guess is too high.")
except Exception:
print("Invalid input, only integers permitted.") | true |
bf035a10ed1781dc9d2e990b532823f2acf83d03 | mattrid93/ProjectEuler | /probs/prob1.py | 451 | 4.21875 | 4 | """Problem 1: Multiples of three and five.
Easy to just perform sum."""
import unittest
def sum_multiples(n):
"""Returns the sum of multiples of three and five below n"""
assert n >= 0
return sum([i for i in range(n) if (not i%3) or (not i%5)])
class TestMultiples(unittest.TestCase):
def test_10(self):
self.assertEqual(sum_multiples(10), 23)
if __name__ == "__main__":
print(sum_multiples(10000))
unittest.main()
| true |
7cd856ab36b7e2bc65b3a4bfa04a8c95db93f6d0 | MarcoC1796/interview_programming_problems | /EPI/7.11_test_whether_a_singly_linked_list_is_palindromic.py | 2,204 | 4.15625 | 4 | # Problem: write a program that tests whether a sinlgy linked list is palindromic.
class ListNode:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
def __str__(self):
result = []
head = self
while head:
result.append(str(head.data)+" -> ")
head = head.next
return ''.join(result)
def __eq__(self, L):
iter1 = self
iter2 = L
while iter1 and iter2:
if iter1.data != iter2.data:
return False
iter1 = iter1.next
iter2 = iter2.next
return (not iter1) and (not iter2)
# EPI Judge: is_list_palindromic.py
def is_linked_list_a_palindrome(L):
def reverse_list(start):
if not start.next:
return
prev_head = start.next
while prev_head.next:
temp = prev_head.next
prev_head.next = temp.next
temp.next = start.next
start.next = temp
dummy_head = ListNode(next=L)
iterator_slow, iterator_fast = dummy_head, dummy_head
while iterator_fast.next and iterator_fast.next.next:
iterator_fast = iterator_fast.next.next
iterator_slow = iterator_slow.next
reverse_list(iterator_slow)
second_half_iter = iterator_slow.next
first_half_iter = dummy_head.next
while second_half_iter:
if second_half_iter.data != first_half_iter.data:
reverse_list(iterator_slow)
return False
second_half_iter = second_half_iter.next
first_half_iter = first_half_iter.next
reverse_list(iterator_slow)
return True
def array_to_list(L):
dummy_head = ListNode()
previous = dummy_head
for e in L:
current = ListNode(data=e)
previous.next = current
previous = current
return dummy_head.next
if __name__ == "__main__":
L = [2, 5, 3, 1, 3, 5, 3, 4, 2, 5, 5, 6, 3, 2, 2, 4, 3, 4, 5, 6,
6, 5, 4, 3, 4, 2, 2, 3, 6, 5, 5, 2, 4, 3, 5, 3, 1, 3, 5, 2]
L1 = array_to_list(L)
L2 = array_to_list(L)
assert L1 == L2
result = is_linked_list_a_palindrome(L2)
assert L1 == L2
assert result == True
| true |
092e978a9c664d36443ad76361a61566661e7de8 | MarcoC1796/interview_programming_problems | /EPI/15.5_generate_power_set.py | 1,034 | 4.34375 | 4 | # Problem: Write a function that takes as input a set and returns its power set
# input: [1,2,3]
# output: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
def generate_power_set(input_set):
'''
INPUT:
input_set: List[int], set of elements represented as a list
OUTPUT:
power_ser: List[List[int]], power set of input_set
'''
# recursive rule: we compute all sets with curr_element and all sets withoud curr_element
def generate_sets(curr_element, curr_set):
if curr_element == len(input_set):
power_set.append(curr_set[:])
else:
# with curr_element
generate_sets(curr_element + 1, curr_set)
# without curr_element
curr_set = curr_set + [input_set[curr_element]]
generate_sets(curr_element + 1, curr_set)
power_set = []
generate_sets(0, [])
return power_set
if __name__ == "__main__":
tests = [[1,2,3], [1,2,3,4,5,6]]
for test in tests:
print(generate_power_set(test)) | true |
4b379c1b86574d5529ecc3d80451eb0518c70b4f | sqhmaker/python- | /2020.8.19/06-元组获取键值.py | 766 | 4.34375 | 4 | """
现有字典``dict1 = {'name':'chuanzhi','age':18}``
要求:
1.使用循环将字典中所有的键输出到屏幕上
2.使用循环将字典中所有的键输出到屏幕上
3.使用循环将字典中所有的键值对输出到屏幕上
输出方式:
name:chuanzhi
age:18
#### 训练目标
1. for循环的使用复习
2. 学会如何获取字典所有的键
3. 学会如何获取字典所有的值
4. 学会如何获取字典所有的键值对
"""
dict1 = {'name': 'chuanzhi', 'age': 18}
for key in dict1.keys():
print(key)
for value in dict1.values():
print(value)
for key, value in dict1.items():
# print(f"{key}:{value}")
print(key, ':', value)
| false |
fe778918b17c2215a160b9c13f313b41592a57c3 | curiouskaran/pydev | /python_practice/program_13.py | 791 | 4.53125 | 5 | #python practice - program_13.py
__author__ = 'karan sharma'
'''Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence
to generate.
(Hint The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in
the sequence.'''
print'enter the first number in the series',
start = int(raw_input('-->'))
print'enter the number upto which fibonnaci sequence required',
end = int(raw_input('-->'))
def fibonnaci(n):
if n == 0 or n == 1:
return n
else:
return fibonnaci(n-1)+fibonnaci(n-2)
print [ fibonnaci(n) for n in xrange(start,end) ] | true |
5bc2adfd6e0b3c8bba8224ba0fb3ac537e759a6f | james-chang727/Python_practice | /006 functions exercise/pyramid.py | 1,027 | 4.1875 | 4 | MARGIN = 10
def pyramidLine(symbol, lineNumber, height):
line = ""
line += spacesForPyramidLine(lineNumber, height)
line += symbolsForPyramidLine(symbol, lineNumber)
line += "\n"
return line
def symbolsForPyramidLine(symbol, lineNum):
lineSymbols = ""
for symbolsCount in range((lineNum * 2) - 1):
lineSymbols += symbol
return lineSymbols
def spacesForPyramidLine(lineNum, height):
lineSpaces = ""
for spacesCount in range(MARGIN + height + 1 - lineNum):
lineSpaces += " "
return lineSpaces
def pyramidString(character, height):
pattern = "\n"
for lineCount in range(height):
pattern += pyramidLine(character, lineCount, height)
return pattern
def main():
height = int(input("\n\tEnter the number of lines for the pyramid: "))
brickCharacter = input("\tEnter the character from which the pyramid should be made: ")
print(brickCharacter)
print(pyramidString(brickCharacter, height))
if __name__ == "__main__":
main()
| true |
bec82edf83804114b10125583c28dc876d3a2c01 | james-chang727/Python_practice | /002 simple IO exercise/age_calc_advanced.py | 1,285 | 4.21875 | 4 | # This program calculates how old someone will be in a given year and month,
# after prompting for the current year, month and user's age.
def main():
year_now = int(input("Enter the current year then press RETURN: "))
int(input("Enter the current month (a number from 1 to 12): "))
age_now = int(input("Enter your current age in years: "))
month_born = int(input("Enter the month in which you were born (a number from 1 to 12): "))
another_year = int(input("Enter the year in which you wish to know your age: "))
another_month = int(input("Enter the month in this year: "))
another_age = another_year - (year_now - age_now)
if another_month < month_born:
another_age -= 1
another_age_months = 12 + another_month - month_born
else:
another_age_months = another_month - month_born
if another_age_months == 1:
print("Your age in {}/{}: {} years and 1 month".format(another_month, another_year, another_age))
elif another_age_months == 0:
print("Your age in {}/{}: {} years".format(another_month, another_year, another_age))
else:
print("Your age in {}/{}: {} years and {} months".format(another_month, another_year, another_age, another_age_months))
if __name__ == "__main__":
main() | true |
afbf371a268b74c4456f6f39870340db5b04f186 | james-chang727/Python_practice | /004 loops exercise/star_triangles.py | 482 | 4.28125 | 4 | tri_num = int(input("Enter the number of lines for the triangle: "))
# triangle of stars of a height given by the user
for i in range(tri_num+1):
print("\t" + "*" * i)
print("\n")
# triangle of stars of a height upside down
for i in range(tri_num+1):
print("\t" + "*" * (tri_num - i))
print("\n")
# isosceles triangle: print an upside down height triangle with space
for i in range(tri_num+1):
print("\t" + " " * (tri_num - i), end = "")
print("*" * (2*i + 1))
| false |
a7a6ecede87d42e38410da980607c31167e04fc6 | szparag3/sql | /assignment3b.py | 876 | 4.25 | 4 |
#Import the sqlite3 library.
import sqlite3
#Connect to the database.
with sqlite3.connect("newnum.db") as conn:
#Establish a cursor.
cursor = conn.cursor()
prompt = """
Select the operation that you want to perform [1-5]:
1. Average
2. Max
3. Min
4. Sum
5. Exit
"""
#Using an infinite loop, continue to ask the user
while True:
#get user input
x = raw_input(prompt)
#if user enters any choice from 1-4
if x in set(["1","2","3","4"]):
#parse the corresponding operation text
operation = {1: "avg", 2: "max", 3:"min",4:"sum"}[int(x)]
#retrive data
cursor.execute("SELECT {}(num) from numbers".format(operation))
#fetchone() retrievs one record from the query
get = cursor.fetchone()
#output result to screen
print operation + ": %f" % get[0]
#if user enters 5
elif x == "5":
print "Exit"
#exit loop
break
| true |
c241c37d919924b3e392f8df9d3250d5c2a5e9b0 | quanhoang1408/QuanHoang-C4T12 | /mnhd/mnhd8.py | 670 | 4.25 | 4 | character= {
"name" : "light",
"age" : 17,
"streghth" : 8,
"defense" : 10,
"backpack" : ["shield","breadloaf"],
"gold" : 100,
"level" : 2
}
print(character)
skill1 ={
"Name" : "Tackle",
"Minimum level" : 1,
"Damage" : 5,
"Hit rate" : 0.3
}
skill2 = {
"Name": "Quick attack",
"Minimum level": 2,
"Damage": 3,
"Hit rate": 0.5
}
skill3 = {
"Name" :"Strong kick",
"Minimum level":4,
"Damage" :9,
"Hit rate" :0.2
}
skill=[skill1,skill2,skill3]
for i in range(3):
print(i+1,skill[i])
n = int(input("choose the skill u want"))
if n<3:
print("ok")
else :
print("your level is not enough")
| false |
612df76207f2e621678f0bf6de1febde72dba1d3 | DongZii0201/gentle-hands-on-python | /modules/module.py | 1,197 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
def getMeanValue(valueList):
"""
Calculate the mean (average) value from a list of values.
Input: list of integers/floats
Output: mean value
"""
valueTotal = 0.0
for value in valueList:
valueTotal += value
numberValues = len(valueList)
return (valueTotal/numberValues)
def compareMeanValueOfLists(valueList1,valueList2):
"""
Compare the mean values of two lists of values.
Input: valueList1, valueList2
Output: Text describing which of the valueLists has the highest average value
"""
meanValueList1 = getMeanValue(valueList1)
meanValueList2 = getMeanValue(valueList2)
if meanValueList1 == meanValueList2:
outputText = "The mean values are the same ({:.2f}).".format(meanValueList1)
elif meanValueList1 > meanValueList2:
outputText = "List1 has a higher average ({:.2f}) than list2 ({:.2f}).".format(meanValueList1,meanValueList2)
else:
# No need to compare again, only possibility left
outputText = "List2 has a higher average ({:.2f}) than list1 ({:.2f}).".format(meanValueList2,meanValueList1)
return outputText
| true |
3e3b9fe66b816bec534eae85d1d3d37f217995a7 | sandhu1/SnakesAndLadders | /Snakes and Ladders(Assignment-1)/main.py | 2,771 | 4.3125 | 4 | # SNAKES AND LADDERS GAME
# Importing useful modules created in project directory
from player_position import *
from configuration import *
class StartGame:
# Method involving all important steps.
def start_rolling(self):
print("WELCOME TO SNAKES AND LADDERS")
# Enter names of players.
player1 = PlayerPosition(input("ENTER FIRST PLAYER'S NAME : "))
player2 = PlayerPosition(input("ENTER SECOND PLAYER'S NAME : "))
# Configure snakes and ladders by specifying their start and end points.
conf = ConfigureSnakesAndLadders()
conf.enter_snakes()
conf.enter_ladders()
conf.show_snakes_and_ladders()
# Show initial positions of both players i.e 0 .
player1.display_position()
player2.display_position()
# An infinite loop runs until a player wins.
while True:
# Steps and functions for player1.
print("{}'s turn".format(player1.name))
roll = input("PRESS ENTER TO ROLL THE DICE")
player1.new_position()
player1.check_snake()
player1.check_ladder()
# Break the loop when a player wins.
if player1.check_win():
break
player1.display_position()
# Give one more turn if a dice shows "6"
if player1.dice_count == 6:
print("!!!You got 6 ,Press ENTER for another turn!!!")
player1.new_position()
player1.check_snake()
player1.check_ladder()
if player1.check_win():
break
player1.display_position()
print("\n")
print("--------------------------------------")
print("\n")
# Steps and functions for player2
print("{}'s turn".format(player2.name))
roll = input("PRESS ENTER TO ROLL THE DICE")
player2.new_position()
player2.check_snake()
player2.check_ladder()
if player2.check_win():
break
player2.display_position()
if player2.dice_count == 6:
print("!!!You got 6 .Press ENTER for another turn!!!")
player2.new_position()
player2.check_snake()
player2.check_ladder()
if player2.check_win():
break
player2.display_position()
print("\n")
print("--------------------------------------")
print("\n")
if __name__ == '__main__':
# main driver program
match = StartGame()
match.start_rolling()
| true |
9c4a1bde9dc144add7f9ba25623c2f269334ce40 | addherbs/LeetCode | /Explore_Top_Interview_Questions/Hamming Distance.py | 907 | 4.1875 | 4 | """
Hamming Distance
Solution
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
"""
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
count = 0
set_bit = 1
for i in range(32):
if set_bit & x != set_bit & y:
count += 1
set_bit <<=1
return count
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
count = 0
exored = x ^ y
while exored:
if exored & 1:
count += 1
exored >>=1
return count | true |
d7ed1a72cdd1248017a56f11062d2aa431f5e616 | damienlevitt/CMPE-130 | /lib/hw4/directed_graph.py | 2,281 | 4.125 | 4 | class Digraph:
"""This class implements a directed graph with nodes represented by integers. """
def __init__(self):
"""Initializes this digraph."""
self.edgeNum = 0
self.nodeList = set()
self.parents = dict()
self.children = dict()
def add_node(self, node):
"""adds vertices to your graph"""
if node not in self.nodes:
self.nodeList.add(node)
self.parents[node] = dict()
self.children[node] = dict()
else:
return "Node in graph already"
def add_edge(self, first, last, weight):
"""creates edges between two given vertices in your graph"""
if first not in self.nodeList:
self.add_node(first)
if last not in self.nodeList:
self.add_node(last)
self.parents[last][first] = weight
self.children[first][last] = weight
self.edgeNum += 1
def has_edge(self, first, last):
"""checks if a connection exists between two given nodes in your graph"""
return first in self.nodeList and last in self.children[first]
def get_edge_weight(self, first, last):
"""" Returns weight of particular edge from node first to node last """
return self.children[first][last]
def remove_edge(self, last, first):
"""removes edges between two given vertices in your graph"""
del self.parents[last][first]
del self.children[first][last]
self.edgeNum -= 1
def remove_node(self, node):
"""removes vertices from your graph"""
if node not in self.nodeList:
print("Node not in graph, unable to delete")
return
self.edgeNum -= len(self.parents[node]) + len(self.children[node])
# Deletes link to parent
for link1 in self.parents[node]:
del self.children[link1][node]
# Deletes link to Child
for link2 in self.children[node]:
del self.parents[link2][node]
# Deletes nodes from dictionaries
del self.parents[node]
del self.children[node]
self.nodeList.remove(node)
def contains(self, node):
"""checks if your graph contains a given value"""
return node in self.nodes
| true |
efc359e54de02298b585656fc29e137a95aa1053 | vinit-ww/Assignments | /python/GAME_15JULY2016.py | 454 | 4.21875 | 4 | # Create a list.
elements = []
#loop variables
i=0
j=0
# Append empty lists in first two indexes.
elements.append([])
elements.append([])
# Add elements to empty lists.
elements[0].append(1)
elements[0].append(2)
elements[1].append(3)
elements[1].append(4)
# Display top-left element.
print(elements[0][0])
# Display entire list.
print(len(elements))
while ( i < len(elements) ):
i=i+1
while ( j < len(elements) ):
j=j+1
print elements[i][j]
| true |
5c0f71d8986af2a8a63622697add21077a91d91e | vinit-ww/Assignments | /18july2016/INPUT_INT.py | 430 | 4.40625 | 4 | #using raw_input get input convert it to string and show at output
print "Enter your name :"
name = raw_input()
#using raw_input to get input and explicitly converting it to int both cases are same
print "Enter your phone number :"
number = raw_input()
number = int(number);
print "Enter your pin code :"
pin = int(raw_input())
print "Your name is %s and your phone number is %d and pincode of city is %d "%( name , number , pin)
| true |
1d54084e58d9f1c778a0f09b2be71eec9d05d4d1 | vinit-ww/Assignments | /python/CSV.py | 2,195 | 4.34375 | 4 | import csv
import sqlite3
class Read:
def csv_reader(self,file_path):
"""
read csv file
"""
new_list = []
file_obj=open(file_path,"r")
reader=csv.reader(file_obj)
for row in reader :
new_list.append(row)
return new_list
def insert(self,my_List):
#connecting database
conn=sqlite3.connect('myDatabase')
#once we have the connection we can create the cursor object to execute() query
c = conn.cursor()
#Create table
c.execute('''CREATE TABLE info( FirstName text ,LastName text ,EmailId text )''')
for t in my_List :
c.execute("insert into info(FirstName , LastName ,EmailId) values (?,?,?)",(t[0],t[1],t[2],))
if (c.execute("SELECT * FROM info ")):
r =c.fetchall()
for member in r:
print member
"""
#select statement
str1=List[0]
str2=List[1]
str3=List[2]
if (c.execute("SELECT * FROM info WHERE FirstName like '%s'" % str1)):
print c.fetchall()
if (c.execute("SELECT * FROM info WHERE LastName like '%s'" % str2)):
print c.fetchall()
if (c.execute("SELECT * FROM info WHERE EmailId like '%s'" % str3)):
print c.fetchall()
"""
#save changes
conn.commit()
#close database
conn.close()
#creating object
obj = Read()
#Insert the path of the file
f = raw_input('Enter path of the csv file :')
#calling method
my_List = obj.csv_reader(f)
obj.insert(my_List)
"""
#creating a list
obj.a = []
obj.Firstname=raw_input('Enter the first name \n')
obj.Lastname=raw_input('Enter the Last name \n')
obj.EmailId=raw_input('Enter the Email Id \n')
(obj.a).append(obj.Firstname)
(obj.a).append(obj.Lastname)
(obj.a).append(obj.EmailId)
obj.insert(my_List,obj.a)
"""
| true |
d4a6f4c766e7c7e45e97d98cdcd5395814798fe5 | jic496/ECE180-group10 | /Data_input_and_cleaning.py | 2,194 | 4.15625 | 4 |
# coding: utf-8
# In[ ]:
def file_in(file_name):
'''
First stage of data input, this function takes the raw data from the BTS website, removes invalid (empty)
inputs and splits each row of data into lists.
https://www.transtats.bts.gov/OT_Delay/ot_delaycause1.asp?display=chart&pn=1
:param: file_name
:type: str
'''
assert isinstance(file_name,str)
f = open(file_name,'r')
data = f.readlines()
data = data[1:] # get rid of first row (headers)
data_new = []
for i in data:
data_line = i.split(',') # split rows into lists
if '' not in data_line: # remove invalid entries
data_new.append(data_line)
return data_new
def data_clean(x): #data_new
'''
This function takes the output list from the previous function and cleans up the data. It removes unwanted columns
and format the entries. The output of the function is a list of lists in the form of the following:
[0.year, 1.month, 2.airline code, 3.airport code, 4.total number of flight, 5.total number of delayed flight*,
6.total delayed minutes*, 7.percentage of delayed flight, 8.average delay minutes per delayed flight]
*our interest of delayed flights does not include weather/nas/security delay, since it is not caused by the airline.
'''
assert isinstance (x,list)
clean_data = []
for i in x:
new_line = []
new_line.append(int(i[0])) #year, convert to integers
new_line.append(int(i[1])) #month, convert to integers
new_line.append(i[2][1:-1]) #Airline, convert from '"x"' to 'x'
new_line.append(i[4][1:-1]) #Airport, convert from '"x"' to 'x'
new_line.append(float(i[7])) #total number of flights
new_line.append(round(float(i[9])+float(i[13]),2)) #total number of delayed flights
new_line.append(float(i[16])+float(i[17])+float(i[21])) #total delayed minutes
new_line.append(round(new_line[5]/new_line[4]*100,2)) #percentage of delayed flight in %
new_line.append(round(new_line[6]/(new_line[5]+0.00001),2)) #average delayed minutes per delayed flight
clean_data.append(new_line)
return clean_data
| true |
c0a9fef2f0e018a864a643b6b9266b4d856490cf | brunogringo/pythonBasic | /exercicio5-estruturas-de-lacos.py | 940 | 4.21875 | 4 | # Faça um programa que leia a quantidade de pessoas que serão convidadas para uma festa.
# Após isso o programa irá perguntar o nome de todas as pessoas e montar uma lista de convidados e mostrar essa lista.
# Build a program to receive a number of peoples to be invited to a party.
# After that the program will ask the name for each person invited, build a list and then show this list.
quantidade = int(input('Digite o número de convidados: '))
convidados = []
i = 0
for i in range(quantidade):
nome = input('Qual o nome do ' + str(i+1) + 'º convidado? ')
convidados.append(nome)
i += 1
for convidado in convidados:
print(convidado)
print('Same form, but in english')
quantity = int(input('How many invites: '))
invites = []
i = 0
for i in range(quantity):
name = input('What is the name of the ' + str(i+1) + 'º invited? ')
invites.append(name)
i += 1
for invite in invites:
print(invite) | false |
6059379b0d4afa53542592872c72743e54b0b771 | Kevin-Howlett/MIT-python3-coursework | /how_many.py | 359 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 19:07:34 2019
@author: kevinhowlett
"""
#program takes a dictionary with lists as values
#and returns an integer number of values in the dictionary
def how_many(aDict):
num_values=0
for v in aDict.values():
for i in v:
num_values+=1
return num_values | true |
3127b4e227d728b737938c7d803b99af52e5796e | spersat/python-learning-Aug-7pm | /test.py | 1,745 | 4.28125 | 4 | '''
##################### commands #######################"
id() --> to retrieve the info about the location of a data
print() --> to print info in the terminal
type() --> return the type of a variable
import keyword
print(keyword.kwlist)
--> return the list of the keywords (33) in python
##################### Rules #######################"
Identifiers:
The allowed start for an identifier name iq: a - z, A - Z, 0-9, _
Identifier should not start digit
Python programm/identifers are case sensitive
There are 33 keywords or reserved words that cannot be used for creating an identifier name
There is no lenght limit in Identifier
_a --> protected variable (??)
__a --> private variable (??)
__a___ ---> magic variable (??)
end operators
\n to go to the next line
end="" to don't go to the nextr line at the end of the print command
print("Hello")
print("I am good")
--> Hello
I am good
print("Hello", end="")
print("I am good")
--> HelloI am good
##################### Operators #######################"
Arithmetic operaors
5+2: +, -, *, /, % and //, **
Relational operators
<, >, <=, >=, ==, !=
==> return a boolean (True or False)
Unary Operators
- , +
Assignmet Operators
Logical Operators
Identity Operators
bitwise Operators
Membership Operators
'''
print("hello", end="")
a=10
print (id(a))
print(a)
print("a")
a,b,c = 10,20,30
print(a,b,c)
age=60
job="developper"
salary="20000"
print('I am a {0}, my am {1} years old and my salary is {2}' .format(job,age,salary))
x = int(input("Please Enter First Number:"))
y = int(input("Please Enter Second Number:"))
print("Sum of two number:", x+y)
print("Sum of two numbers:", int(input("First Number"))+int(input("Enter Second Number")))
| true |
92d1790d47d906ef199d63d0a0ff409e595e650f | peterCcw/subset_sum_problem | /functions/bf.py | 1,618 | 4.125 | 4 | def subset_sum_BF(set, target, n):
"""
Finds in given set subset whose sum is equal or as close as possible to
given target. Uses recursive brute force algorithm. Needs set of numbers,
target value and size of set as an input, returns tuple of vars:
is sum of subset equal to target, subset sum, subset as list and table.
:param set: list<int>
:param target: unsigned int
:param n: unsigned int
:return: tuple (boolean, unsigned int, list)
"""
if n == 0 or target == 0:
return False, 0, []
# if element is bigger than target, it is not considered
elif set[n - 1] > target:
return subset_sum_BF(set=set, target=target, n=n-1)
# comparison of two cases: element included and item excluded,
# bigger is returned
else:
# saving tuples of sum of subset and subset into vars
included = subset_sum_BF(set=set, target=target-set[n-1], n=n-1)
excluded = subset_sum_BF(set=set, target=target, n=n-1)
# choosing bigger sum of elements
included_sum = set[n - 1] + included[1]
excluded_sum = excluded[1]
# initializing output vars
output_set = []
output_val = 0
does_subset_exist = False
if included_sum >= excluded_sum:
included[2].append(set[n - 1])
output_set = included[2]
output_val = included_sum
else:
output_set = excluded[2]
output_val = excluded_sum
if output_val == target:
does_subset_exist = True
return does_subset_exist, output_val, output_set | true |
01fdbf34ee9926d92314aced87ebb2fcb216ec0e | Hadeer-Elsaeed/Thinkpython2-Exercises | /variables & expressions.py | 1,831 | 4.28125 | 4 | # • We’ve seen that n = 42 is legal. What about 42 = n ?
# Syntax error
# • How about x = y = 1 ?
# No problem x will be equal 1 and also y.
# • In some languages every statement ends with a semi-colon, ; . What happens if you put a
# semi-colon at the end of a Python statement?
# no problem with semi-colon,it allows to add more statements in same line but it's not preferred.
#• What if you put a period [.] at the end of a statement?
# it will be syntax error.
# • In math notation you can multiply x and y like this: xy. What happens if you try that in Python?
# it consider this is a variable 'xy'
# 1. The volume of a sphere with radius r is 3 4 πr 3 . What is the volume of a sphere with radius 5?
from math import pi , pow
def volume(r):
return 4/3 *pi* pow(r,3)
print(volume(5))
# Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs
# $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for
# 60 copies?
def cost(number):
cost_piece = (24.95 - (40/100 * 24.95)) + 3
return f"cost is {cost_piece}" if number == 1 else "cost is "+ str(cost_piece+ number * 0.75)
print(cost(60))
# If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at
# tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
second = 1
minute = 60 * second
hour = 60 * minute
time_for_leave_home = 6 * hour + 65 * minute
time_for_easy_pace = 2 * (8 * minute + 15 * second)
time_for_tempo = 3 * (7 * minute + 12 * second)
total_time = time_for_leave_home + time_for_easy_pace +time_for_tempo
hours = total_time // hour
part_hour = total_time % hour
minutes = part_hour // minute
seconds = part_hour % minute
| true |
ea02980e66101a89142cc2eb618811d01c26d032 | mmitiushkin/PythonAlgorithms | /lesson-1/9.py | 416 | 4.125 | 4 | # 9. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
a = int(input('1: '))
b = int(input('2: '))
c = int(input('3: '))
middle = a
if a < b < c or a > b > c:
middle = b
elif a < c < b or a > c > b:
middle = c
print(f'Среднее число из {a, b, c} это {middle}')
| false |
3ad041560ed980e0d2ab069717633ea0f2b5d6bc | strawberry-code/practice-python | /ex-031-guess-letters/guess_letters.py | 2,240 | 4.40625 | 4 | # Author: Cristiano Cavo
# Date: 2019-08-28
# From: http://www.practicepython.org/exercise/2017/01/02/31-guess-letters.html
# This exercise is Part 2 of 3 of the Hangman exercise series. The other
# exercises are: Part 1 and Part 3.
#
# Let’s continue building Hangman. In the game of Hangman, a clue word is given
# by the program that the player has to guess, letter by letter. The player
# guesses one letter at a time until the entire word has been guessed. (In the
# actual game, the player can only guess 6 letters incorrectly before losing).
#
# Let’s say the word the player has to guess is “EVAPORATE”. For this exercise,
# write the logic that asks a player to guess a letter and displays letters in
# the clue word that were guessed correctly. For now, let the player guess an
# infinite number of times until they get the entire word. As a bonus, keep
# track of the letters the player guessed and display a different message if the
# player tries to guess that letter again. Remember to stop the game when all
# the letters have been guessed # correctly! Don’t worry about choosing a word
# randomly or keeping track of the number of guesses the player has remaining -
# we will deal with those in a future exercise.
#
# An example interaction can look like this:
#
# >>> Welcome to Hangman!
# _ _ _ _ _ _ _ _ _
# >>> Guess your letter: S
# Incorrect!
# >>> Guess your letter: E
# E _ _ _ _ _ _ _ E
# ...
# And so on, until the player gets the word.
def guessWord(word):
secretLetters = list(word)
del secretLetters[-1] # removes the \n
guessedLetters = ["_"] * len(secretLetters)
stop = False
while not stop:
if "_" not in guessedLetters:
print("you win!")
stop = True
else:
print(guessedLetters)
userLetter = input("give a letter (0 to stop) > ")
if userLetter == "0":
stop = True
elif userLetter in secretLetters:
for i in range(len(secretLetters)):
if secretLetters[i] == userLetter:
guessedLetters[i] = userLetter
print(secretLetters)
print(guessedLetters)
def main():
word = "EVAPORATE"
guessWord(word)
main()
| true |
525790ff307bd22e77c5b3458b275d4f7664bd69 | strawberry-code/practice-python | /ex-023-file-overlap/file_overlap.py | 1,477 | 4.15625 | 4 | # Author: Cristiano Cavo
# Date: 2019-08-27
# From: http://www.practicepython.org/exercise/2014/12/14/23-file-overlap.html
# Given two .txt files that have lists of numbers in them, find the numbers that
# are overlapping. One .txt file has a list of all prime numbers under 1000, and
# the other .txt file has a list of happy numbers up to 1000. (If you forgot,
# prime numbers are numbers that can’t be divided by any other number. And yes,
# happy numbers are a real thing in mathematics - you can look it up on
# Wikipedia. The explanation is easier with an example, which I will describe
# below.)
# File one: http://www.practicepython.org/assets/primenumbers.txt
# File two: http://www.practicepython.org/assets/happynumbers.txt
# Notes: I decided to read from the file generated in the exercise number 21 and
# to looking for the frequency of some given words
""" # # # # -<( Bootcamp )>- # # # #
with open('file_to_read.txt', 'r') as open_file:
text = open_file.read()
"""
def getText(filepath):
with open(filepath, "r") as open_file:
text = open_file.read()
return text
def findOverlaps(listOne, listTwo):
listThree = []
for e in listOne:
if e in listTwo:
listThree.append(e)
return listThree
def main():
listOne = getText("happynumbers.txt").split()
listTwo = getText("primenumbers.txt").split()
overlaps = findOverlaps(listOne, listTwo)
print("overlaps: {}".format(overlaps))
main()
| true |
22602d5a45a8ca582b79730b546f4dafa1679970 | strawberry-code/practice-python | /ex-050-mac-generator/mac-generator.py | 577 | 4.40625 | 4 | # course: python self training
# exercise: 14
# date: Oct 11 2020
# username: shinigami
# name: Cristiano Cavo
# description: write a cli program capable of generate random mac addresses
# filename: mac-generator.py
# define digits
digits = "0987654321ABCDEF"
# define generator
import random
import pyperclip
def generator():
mac = ""
for i in range(6):
for j in range(2):
mac += digits[int(random.randrange(len(digits)))]
if(i < 5):
mac += ":"
pyperclip.copy(mac)
print("the generate MAC address is: ",mac,"and has been copied to the clipboard")
return
generator() | true |
f2dc48dcb1fd7e15eb71f0c8580e574ed87d4623 | strawberry-code/practice-python | /ex-052-distance-converter/distance-converter.py | 1,387 | 4.1875 | 4 | # course: python self training
# exercise: 16
# date: Oct 11 2020
# username: shinigami
# name: Cristiano Cavo
# description: write a cli program that works as a rhymary for a given word set and a word given as input
# filename: electronic-rhymary.py
# define menu
def menu():
print("""
distance converter:
[1] metres to yards
[2] yards to metres
[3] centimetres to inches
[4] inches to centimetres
[5] kilometres to miles
[6] miles to kilometres
[0] exit
""")
c = int(input(" > "))
if(c == 0):
return
elif(c == 1):
val = float(input("give metres: "))
print(metresToYards(val),"yards")
elif(c == 2):
val = float(input("give yards: "))
print(yardsToMetres(val),"metres")
elif(c == 3):
val = float(input("give centimetres: "))
print(centimetresToInches(val),"inches")
elif(c == 4):
val = float(input("give inches: "))
print(inchesToCentimetres(val),"centimetres")
elif(c == 5):
val = float(input("give kilometres: "))
print(kilometresToMiles(val),"miles")
elif(c == 6):
val = float(input("give miles: "))
print(milesToKilometres(val),"kilometres")
menu()
def metresToYards(m):
return float(m*1.09)
def yardsToMetres(y):
return float(y/1.09)
def inchesToCentimetres(i):
return float(i*2.54)
def centimetresToInches(c):
return float(c/2.54)
def kilometresToMiles(k):
return float(k/1.61)
def milesToKilometres(m):
return float(m*1.61)
menu()
| false |
479fc22c019925d73e6dd95a6e97507526ed7832 | strawberry-code/practice-python | /ex-039-max-from-2-and-3-integers/max-from-2-and-3-integers.py | 665 | 4.3125 | 4 | # course: python self training
# exercise: 3
# date: Oct 3 2020
# username: shinigami
# name: Cristiano Cavo
# description: learn how to make conditional ifs, be aware of colons, indentation! and elif!
# filename: max-from-2-and-3-integers.py
# declare some integers
apples = 2
watermelons = 3
lemons = 5
# compare apples and lemons, give the max
if(apples > lemons):
print("we have more apples than lemons")
else:
print("we have more lemons than apples")
# compare all!
if(apples > lemons and apples > watermelons):
print("we have many apples!")
elif(lemons > apples and lemons > watermelons):
print("we have many lemons!")
else:
print("we have many watermelons!") | true |
ddd25a328298323be43acbc61d5fd7e938d22697 | TI234/Data-structure-using-python | /Sorting/Counting_Sort.py | 1,360 | 4.15625 | 4 | #Counting_Sort.py
#----------------------------------------------
# Logic for counting Sort:
#----------------------------------------------
def CountingSort(A,maxValue,minValue):
Temp_Array = []
length_A = len(A)
#----------------------------------------------
# Creating Temp array:
#----------------------------------------------
for i in range (minValue,(maxValue+1)):
Temp_Array.append(0)
print(Temp_Array)
#----------------------------------------------
#Counting the elements and storing in temporary Array
#----------------------------------------------
for i in range(len(A)):
Temp_Array[A[i]-minValue]+=1
print("counting:\t",Temp_Array)
#----------------------------------------------
# Logic for Counting Sort
#----------------------------------------------
x = 0
for i in range (len(Temp_Array)):
if Temp_Array[i] != 0:
for j in range (Temp_Array[i]):
A[x] = minValue+i
x+=1
print("After Sorting:",A)
#----------------------------------------------
#Taking input of unSorted Array:
#----------------------------------------------
A = []
num = int(input("Enter the size of unsorted Array:"))
for i in range (num):
Element = int(input("Enter the Element:"))
A.append(Element)
print("Before Sorting:\t",A)
minValue = min(A)
maxValue = max(A)
CountingSort(A,maxValue,minValue)
#---------------------------------------------- | true |
a4ded63976eb678b9899c1ddfb00a1edc413df83 | salutdev/ProblemSolving | /TasksInPython/linked_list/reverse_linked_list.py | 824 | 4.21875 | 4 | from linked_list.linked_list_node import LinkedListNode
class Reverse:
def calc(self):
head = LinkedListNode(10)
head.next = LinkedListNode(15)
head.next.next = LinkedListNode(20)
head.next.next.next = LinkedListNode(25)
head.next.next.next.next = LinkedListNode(30)
self.print_linked_list(head)
new_head = self.reverse(head)
self.print_linked_list(new_head)
def reverse(self, head):
prev = None
cur = head
next = None
while cur != None:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
def print_linked_list(self, head):
node = head
while node != None:
print (node.value)
node = node.next
| true |
d924749f6b9899b3f6074107aed06d4119370a2a | andresberejnoi/math | /vector.py | 2,700 | 4.46875 | 4 | import math
class Vector:
'''A vector class. Creates an instance of a vector
object that works under the properties of vectors.'''
def __init__(self, components=[]):
'''Initializes an instance of the Vector class.
components: a list of components coordinates. It starts with x, y, z, ... and so on.'''
# self.mag = mag
self.compo = components
def magnitude(self):
'''Returns the magnitude of the vector, stored in self.magnitude.
It uses the formula |A| = sqrt(A1^2 + A2^2 + ... + An^2) to calculate it.'''
mag =sum([(comp**2) for comp in self.compo])
def dot(self, vector2):
'''Computes the dot product for two vetors'''
if len(self) != len(vector2):
raise ValueError ("Cannot compute the dot product of vectors of different dimensions")
# for i in range(min(len(self), len(vector2))):
new_vec = []
for v1,v2 in zip(self.compo, vector2.compo):
new_vec.append(v1*v2)
return sum(new_vec)
def __len__(self):
return len(self.compo)
def __eq__(self, other):
if self.compo == other.compo:
return True
return False
def __getitem__(self, key):
return self.compo[key]
def __iter__(self):
for component in self.compo:
yield component
def __neg__(self):
new_vec = [-1*comp for comp in self.compo]
return Vector(new_vec)
def __add__(self, vec_2):
if len(self) != len(vec_2):
raise ValueError ("Cannot add two vectors in different dimensions.")
new_vec = []
for i in range(len(self)):
new_vec.append((self.compo[i] + vec_2.compo[i]))
return Vector(new_vec)
def __sub__(self, to_sub):
return self.__add__(-to_sub)
def __mul__(self, to_mult):
if type(to_mult)==int or type(to_mult)==float:
new_vec = []
for item in self.compo:
new_vec.append(item*to_mult)
return Vector(new_vec)
elif type(to_mult)==Vector:
assert(len(self)==len(to_mult))
new_vec = [self[i]*to_mult[i] for i in range(len(self))]
return Vector(new_vec)
def __str__(self):
return str(tuple(self.compo))
# rep = '('
# for comp in self.compo:
# rep += str(comp) + ', '
#
# rep += ')'
# return rep
#
def __repr__(self):
return str(self)
| true |
dde11e6b3338a990ce774a3a0075217e2a599d1a | BestBroBradley/py_library | /app.py | 1,960 | 4.25 | 4 | import utils.operations as operations
welcome = '''
Welcome to your library!
'''
menu = '''
Would you like to:
-View your library (view)
-Add a book to your library (add)
-Delete a book from your library (delete)
-Mark a book as read (update)
-Exit (exit)
'''
goodbye = '''
Thank you for using our service.
'''
def initiate():
print(welcome)
selection = input(menu).lower()
switchboard[selection]()
def view():
library = operations.view_all()
if library:
for book in library:
if book["read"]:
book["read"] = "yes"
else:
book["read"] = "no"
print(f"Title: {book['title']} | Author: {book['author']} | Read? {book['read']}")
else:
print("No titles in library.")
repeat()
def add():
title = input("What title would you like to add? ").title()
author = input(f"Who wrote {title}? ").title()
confirm = input(f"{title} by {author} will be added to your library. Is this ok? (y/n) ")
if confirm.lower() == "y":
result = operations.add_book(title, author)
if result:
print("Added to library!")
else:
print("Item already in library.")
repeat()
def update():
title = input("Which title would you like to mark as 'read'? ").title()
confirm = input(f"You will be updating {title}. Is this ok? (y/n) ")
if confirm.lower() == "y":
operations.update_book(title)
repeat()
def delete():
title = input("Which title would you like to delete? ").title()
confirm = input(f"You will be deleting {title}. Is this ok? (y/n) ")
if confirm == "y":
operations.delete_book(title)
repeat()
def repeat():
selection = input(menu).lower()
switchboard[selection]()
def leave():
print(goodbye)
switchboard = {
"view": view,
"add": add,
"delete": delete,
"update": update,
"exit": leave
}
initiate()
| true |
fa03a4f1755e7f9fe08cf06c91d871e5c450d40c | acharsujan/90Problems | /day29.py | 563 | 4.375 | 4 | #Python function to print common elements in three sorted arrays
def findcommon(ar1, ar2, ar3, n1, n2, n3):
i, j, k = 0, 0, 0
while (i < n1 and j < n2 and k < n3):
if (ar1[i] == ar2[j] and ar2[j] == ar3[k]) :
print (ar1[i])
i += 1
j += 1
k += 1
elif (ar1[i] < ar2[j]):
i +=1
elif(ar2[j] < ar3[k]):
j +=1
else:
k +=1
#Driver program
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
n1 = len(ar1)
n2 = len(ar2)
n3 = len(ar3)
print("common elements are", findcommon(ar1,ar2,ar3,n1,n2,n3)) | false |
05e90f0e4f7822391a79a36887b74b7329aada6c | sunqingliang6/python-practice-sunql | /basicGrammer/jichengBianliang.py | 1,077 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
#子类不会继承父类的私有变量
#创建子类实例时,如果子类定义了构造函数,则只调用子类的构造函数;如果子类未定义构造函数,则执行父类构造函数
class Animal(object):
__privateSun = 'privateSun'
publicQing = 'publicQing'
def __init__(self, name):
print 'zhi xing Animal init'
self.__name = name;
def call(self):
print "Animal call."
def getName(self):
return self.__name
def getPrivateSun(self):
return self.__privateSun
def getPublicQing(self):
return self.publicQing
class Dog(Animal):
def __init__(self):
print 'zhi xing Dog init'
self.__name = 'aaaa';
def call(self):
print "Dog call 'wang wang'."
class Cat(Animal):
def call(self):
print "Cat call 'miao miao'."
pet = Animal('mypet')
print pet.getName()
dog = Dog()
print dog.getName()
print '0 ' + dog.getPrivateSun()
print '1 ' + dog.getPublicQing()
print '2 ' + dog.publicQing
# print dog.__privateSun 报错 | false |
c2cef99ef58a4c77fabcc5e6e305ab48a666ea2d | doncheezy/Lab_Python_02 | /UsingControlStructures.py | 1,012 | 4.125 | 4 | #question 5
theInput = raw_input("Enter integer:")
theInput = int(theInput)
if theInput%2 == 0:
print 'even'
else:
print 'odd'
print "--------"
#question 6
primarySchoolAge = 4
legalVotingAge = 18
presidentialage = 40
officialretirementage = 60
personsAge = input("Enter an age:")
if personsAge <= primarySchoolAge:
print "Too young"
elif personsAge >= legalVotingAge:
print "Remember to vote"
elif personsAge >= presidentialage:
print "Vote for me"
elif personsAge >= officialretirementage:
print "Too old"
print"---------"
#question 7 using for
for i in range(40,-1,-1):
if i%3 == 0:
print i
print"solving question 7 using while loop"
#using while for question 7
i = 40
while i >= 0:
i = i - 1
if i%3 == 0:
print i
#question 8
print"---------"
for i in range(6,30,1):
if i%2 != 0 and i%3 != 0 and i%5 !=0:
print i
print "--------------"
#question 9
n = 0
while n >= 0:
n = n + 1
if 79*n%97 == 1:
print n
break
| false |
6af8baff46b4a1f6adf5587d2d46868f44615caa | ajazahmad1/Python-Basic | /Basic.py | 1,709 | 4.375 | 4 | # print function is used to print the message and value
print("Hello World")
print("-----------------------------------------")
x = 7
y = 5
print((x*y))
print("-----------------------------------------")
a = 10
b = 20
c = a+b
print("Addition of",a,"and",b,"=",c)
print("-----------------------------------")
name = "Ajaz Ahmad"
print("Welcome",name)
print("-------------------------------------")
# IDENTIFY OPERATORS
#identify operators in python are used to determine
# whether a value is of a certain class or type
# is : Returns true if both variable are the same object
# is not : Return true if both variable are not the same object
x = 5
if type(x) is int:
print("Correct")
else:
print("incorrect")
a = 5.8
if type(a) is not float:
print("correct")
else:
print("Incorrect")
print("-------------------------------")
# in : This returns true if the element is found otherwise false
# not in : This return true if the element is not found otherwise true
a = 10
li = [12,45,67,11,27]
if a in li:
print("Yes a is present in list")
else:
print("No a is not present in list")
print("------------------------------------------")
x = 5
li2 = [13,14,17,18,12]
if x not in li2:
print("x is not present in list")
else:
print("x is present in list")
print("------------------------------------")
units = int(input("How many units consumed this month :"))
total_price = (5*units)
Discount = (total_price*10)/100
print("After Discount total bill price",Discount)
print("---------------------------------------")
a = int(input("Enter first value "))
b = int(input("Enter second value "))
c = a
a = b
b = c
print("After swaping",a)
print("After swaping",b)
| true |
23fdd40efcf6f95d52d75e61761a981bc3d9bd26 | prakash-cmyk/my-first-project | /number guessing game.py | 850 | 4.1875 | 4 |
#Random Number Guesser
import random
print("welcome to the Random Number Guesser.!")
x=int(input("please enter the first value "))
y=int(input("please enter the second value"))
random_number=random.randint(x,y)
guess=None #x<=N<=y
attempts=0 #attempts the user has made
guessed= False
while(not guessed):
guess=input("please enter a guess between x and y")
if guess.isdigit():
guess=int(guess)
if guess>random_number:
print("guess is too high.!")
elif guess<random_number:
print("guess is too low.!")
else:
guessed=True
attempts+=1
else:
print("invalid input , please try again.")
# while loop stopped running
print("you guessed it!\n it took you",attempts,"attemps to guess ", random_number)
| true |
db0d955fc58751beba908bf4418fd0e6082cddf4 | CaseyScott/python-testing | /python.py | 1,880 | 4.53125 | 5 | """def count_upper_case(message):
return sum([1 for c in message if c.isupper()])
assert count_upper_case("") == 0, "empty string"
assert count_upper_case("A") == 1, "one upper case"
assert count_upper_case("a") == 0, "one lower case"
assert count_upper_case("!@#$%") == 0, "special characters"
assert count_upper_case("HeLlo") == 2, "two upper case"
assert count_upper_case("Hello- World!") == 2, "two upper case"
print(count_upper_case("Hello* World Hello& World Hello# World"))"""
def even_number_of_evens(numbers):
"""
returns a boolean if the number of even
numbers contained in a list of numbers is even.
"""
#check to see if the list is empty
if numbers == []:
return False
else:
#set a 'number_of_evens' variable that will be incremented each
#time an even number is found
evens = 0
#Iterate over each item and if it's an even number, increment the
#'evens' variable
for number in numbers:
if number % 2 == 0:
evens += 1
if evens == 0:
return False
else:
return evens % 2 == 0
#set of test cases
assert even_number_of_evens([]) == False, "No numbers"
assert even_number_of_evens([2]) == False, "One even number"
assert even_number_of_evens([2, 4]) == True, "Two even numbers"
assert even_number_of_evens([2, 3]) == False, "One even, One odd"
assert even_number_of_evens([2,3,9,10,13,7,8]) == False, "multiple numbers, three are even"
assert even_number_of_evens([2,3,9,10,13,7,8,5,12]) == True, "multiple numbers, four are even"
assert even_number_of_evens([1,3,9]) == False, "No even numbers"
assert even_number_of_evens([]) == False, "special characters"
#If all the test cases pass, print some successful info to the console to let
#the developer know
print("All tests passed!") | true |
f1f3a27060fbcdf3675f6ffebab36784ade45591 | yefeihonours/python_basic_knowledge | /Built-in-functions/zip.py | 1,574 | 4.75 | 5 | '''
zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.
zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.
zip() in conjunction with the * operator can be used to unzip a list:
'''
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print(list(zipped))
# [(1, 4), (2, 5), (3, 6)]
x2, y2 = zip(*zip(x, y))
if x == list(x2) and y == list(y2):
print('equal')
#equal | true |
1e11dcc42159050d59bb8116465189f991055d96 | bbb1991/devlabs-python | /week2/examples/example14.py | 1,066 | 4.15625 | 4 | # coding=utf-8
# Пример работы с set
# Set - структура данных, который не хранит дубли
my_set = {1, 1, 1, 1, 1, 1, 3}
print(my_set)
# добавление
my_set.add(5) # Добавление элемента
my_set.update({10, 20, 30}) # Добавление множества
print(my_set)
# Изменение
# Удаление
my_set.discard(10) # Удаление элемента
my_set.remove(1)
print(my_set)
my_set.difference_update({1, 2, 3}) # Удаление элементов, которые есть во обоих множествах
print(my_set)
# my_set -= {1, 2, 3} # или так
# Работа с set
print(my_set.difference({20, 30})) # Возвращает разницу
print(my_set - {20, 30})
print(my_set.intersection({20, 30})) # Возвращает элементы, которые есть в обоих множествах
print(my_set & {20, 30})
print(my_set.union({-1, -2, -3})) # обьединение двух множеств
print(my_set | {-1, -2, -3})
| false |
39eb9e9593a46d968b35ba853c1c3e263cb81230 | lalebdi/Python_Notes | /exceptions_notes.py | 2,982 | 4.125 | 4 | # The difference between a syntax error and an exception
# syntax error: when the parser detects a syntactically incorrect statement
# like this:
# a = 5, print(a)
# exceptions is when a statment is syntactically correct but might cause an error when executed.
# many types:
# type error: adding a number to string
# a = 5 + "10"
# import error:
# import somemodule that does not exist
# it will raise module not found error.
# name error:
# a = 5
# b = c
# the c is not defined
# it will raise a name error
# file not found error:
# f = open('somefile.txt')
# will raise a file not found error.
# the value error:
# happens when if the function receives the right type but wrong vlaue
# a = [1, 2, 3]
# a.remove(1) -> this is fine
# a.remove(4) -> will raise a value error
# index error:
# when trying to access an index in a list that is not too large
# a[4] -> will raise an index error
# my_dict = { "name" : "Ron"}
# my_dict["age"] -> will raise a key error
# raising an exception:
# when you want to force an exception to occur when a certain condition is met. can be done using raise keyword.
# x = -5
# if x < 0:
# raise Exception('x should be positive')
# another way is using the assert statement. will throw an assertion error if the assertion is not true
# x = -3
# assert (x >= 0), 'x is not positive -> will raise an assertion error. add a guiding message after
# to handle exception (catch exceptons with try - except block )
# try:
# a = 5 /0 # -> raises a zero division error
# except: -> can catch the type of exception by adding "Exception as e" after the except
# print('an error happened')
# try:
# a = 4/0
# except Exception as e:
# print(e)
# it's good practice to pridect the error
# try:
# a = 4/1
# b = a + "5"
# except ZeroDivisionError as e:
# print(e)
# except TypeError as e:
# print(e)
# you can have an else clause to continue if nothing is wrong
# try:
# a = 4/1
# b = a + 5
# except ZeroDivisionError as e:
# print(e)
# except TypeError as e:
# print(e)
# else:
# print("eveything is fine")
# you can also have a finally clause; runs always no matter if there is an exception or not. used for clean up
# try:
# a = 4/1
# b = a + 5
# except ZeroDivisionError as e:
# print(e)
# except TypeError as e:
# print(e)
# else:
# print("eveything is fine")
# finally:
# print("cleaning up....")
# defining our own exceptions:
# by subclassing from the base exception class
class ValuseTooHighError(Exception):
pass
class ValueTooSmallError(Exception):
def __init__(self, message, value):
self.message = message
self.value = value
def test_vlaue(x):
if x > 100:
raise ValuseTooHighError("value is too high")
if x < 5:
raise ValueTooSmallError("value is too small", x)
try:
test_vlaue(200)
except ValuseTooHighError as e:
print(e)
except ValueTooSmallError as e:
print(e.message, e.value) | true |
1c40a611a29e06bb6a0b61a48f59f0db2c614523 | netdevmike/python-programming | /Module1/Ch01_ex32.py | 1,236 | 4.34375 | 4 | # A telephone directory has N lines on each page, and each page has exactly C columns. An entry in any column has a name with the corresponding telephone number. On which page, column, and line is the X th entry (name and number) present? (Assume that page, line, column numbers, and X all start from 1.)
# prompt user for entry a number
Entry_number = input('Enter the number of your entry: ')
# Convert value to integer
Entry_number_int = int(Entry_number) - 1
# Assuming 20 items per colum and 4 columns per page
# Assign columns in a page
Columns = 4
# Assign lines in a page
Lines = 20
# calculate number of items per page
Items = Columns * Lines
# Divide entry number by items and add 1 to find page number
Page = Entry_number_int / Items + 1
# round to the neares whole number and print
print('The page is: ', round(Page))
# Modulus entry by item value and divide by columns and add 1 to find line number
Line_value = (Entry_number_int % Items) / Columns + 1
# round to the nearest whole number and print
print('The line is: ', round(Line_value))
# Modulus entry by item and modules result by column. Than add 1 to find columns
Column_value = (Entry_number_int % Items) % Columns + 1
print('The column is: ', Column_value)
| true |
74a76c7fe831a02c0c0749377b47525da7ad7af5 | netdevmike/python-programming | /Ch06/6.11.py | 1,124 | 4.125 | 4 | safe_input = input(str("Enter a String Type you want to check: "))
test = safe_input("this is a string")
print('"{}" is a {}'.format(test, type(test)))
test = safe_input("this is a string", int)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input("this is a string", float)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input(5)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input(5, int)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input(5, float)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input(5.044)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input(5.044, int)
print('"{}" is a {}'.format(test, type(test)))
test = safe_input(5.044, float)
print('"{}" is a {}'.format(test, type(test)))
def safe_input(prompt, type_=str):
if(type_ not in (str, int, float)):
raise ValueError("Expected str, int or float.")
while True:
test = input(prompt)
try:
ret = type_(test)
except ValueError:
print("Invalid type, enter again.")
else:
break
return ret
| true |
7a4ba81fdd8f12a13551e5dcb559af917424b5ef | netdevmike/python-programming | /Module2/Ch02_ex37.py | 1,305 | 4.125 | 4 | # Write a program to generate the following arithmetic examples.
# Hints:
# (1) Divide-and-conquer: what simpler problem do you need to solve? (2) Consider using strings to build numbers and then convert.
# (3) The range iterator may be helpful.
# read input variables par and score
par = int(input("Enter the par value in the range 3 to 5: "))
while(par < 3 or par > 5):
print("You have entered the invalid par value!!!")
par = int(input("Enter the par value in the range 3 to 5: "))
score = int(input("Enter the user Score: "))
# check whether the par is equal to the score
if par == score:
print("Par")
# Check whether the score is less than the par
elif score < par:
if score == par-3:
print("Albatross")
elif score == par-2:
print("Eagle")
elif score == par-1:
print("Birdie")
else:
print("You are not allowed to score less than 3 under par")
# check whether the score is greater than the par
elif score > par:
if score == par+1:
print("Bogey")
elif score == par+2:
print("Double Bogey")
elif score == par+3:
print("Tryiple Bogey")
elif score > par+3:
print("bad hole")
# end of program
| true |
c5d2584517e8db31536af8d6d04c38ea42f9efb3 | edu-athensoft/stem1401python | /session3_collection/list_demo6.py | 219 | 4.1875 | 4 | # iterating
for fruit in ['apple','peach','pineapple']:
print("I hate", fruit)
mylist = ['apple','peach','pineapple']
for fruit in mylist:
print("I hate", fruit)
for n in [1, 2, 3, 4, 5]:
print(n)
| false |
81eab9751c5a342d4e34bdb029743f5ddfce0f9e | edu-athensoft/stem1401python | /session3_collection/list_demo1.py | 649 | 4.21875 | 4 | # to create a list
# with square brackets
# empty list
a = []
# list of integers
a = [1, 2, 3, 4, 5]
s = ['hello', 'world', 'python']
print(len(s))
# len() -> get the length of a list, get how many items there in the list
# parameter
print(len(a))
# list with mixed datatypes
my_list = [1, "Hello", 3.4, 23,324,24,2,34,234,23412,34,234,324,23,'asd','asdf',4356,23]
print(len(my_list))
n = len(my_list)
print(n)
# nested list
my_list_2 = ["mouse", [8, 4, 6], ['a']]
print(my_list_2)
print(my_list_2[0])
print(my_list_2[1])
print(my_list_2[1][0],my_list_2[1][1],my_list_2[1][2])
#a = [1, 2, 3, 4, 5]
print(a[-1])
# 0 = -0
print(a[-2])
| false |
1c063ed73964a8c1acd31b9c0d19d4cc3d46529e | rajeshanu/rajeshprograms | /loops/demo5.py | 217 | 4.21875 | 4 | d={
"idno":101,
"name":"raj",
"salary":"1234512"
}
#display keys
for x in d:
print(x)
print("------------------")
#display values
for x in d:
print(d[x])
#display both
for x in d:
print(x,d[x]) | false |
0d65d900e19dcd42f6e608d83ed5a64c5616411f | Pramudithananda/psd | /student.py | 2,836 | 4.1875 | 4 | class Student:
def __init__(self, name, grade, class_name):
self.name = name
self.grade = grade
self.class_name = class_name
self.marks = {'Maths': [[], [], []], 'Science': [[], [], []], 'Art': [[], [], []]}
def add_marks(self, subject, term, marks):
if subject in self.marks and 1 <= term <= 3:
self.marks[subject][term-1].append(marks)
else:
print('Invalid subject or term.')
def get_marks(self, subject, term):
if subject in self.marks and 1 <= term <= 3:
return self.marks[subject][term-1]
else:
print('Invalid subject or term.')
def calculate_average_marks(self, subject, term):
marks = self.get_marks(subject, term)
if marks:
return sum(marks) / len(marks)
else:
return None
def display_details(self):
print(f"Name: {self.name}")
print(f"Grade: {self.grade}")
print(f"Class: {self.class_name}")
print("Marks:")
for subject, term_marks in self.marks.items():
print(f"Subject: {subject}")
for term, marks in enumerate(term_marks, start=1):
print(f" Term {term}: {marks}")
def find_max_average(students, subject, term):
max_average = -1
top_student = None
for student in students:
average = student.calculate_average_marks(subject, term)
if average is not None and average > max_average:
max_average = average
top_student = student
if top_student:
print(f"The student with the highest average marks for {subject} in Term {term} is {top_student.name}")
print(f"Average marks: {max_average}")
else:
print(f"No student has marks for {subject} in Term {term}")
def find_lowest_science_marks(students):
lowest_marks = float('inf')
lowest_student = None
for student in students:
marks = student.get_marks('Science', 1) + student.get_marks('Science', 2) + student.get_marks('Science', 3)
if marks and min(marks) < lowest_marks:
lowest_marks = min(marks)
lowest_student = student
if lowest_student:
print(f"The student with the lowest marks in Science is {lowest_student.name}")
print(f"Lowest marks: {lowest_marks}")
else:
print("No student has marks for Science")
def insert_students():
students = []
while True:
name = input("Enter student name (or 'exit' to stop): ")
if name.lower() == 'exit':
break
grade = int(input("Enter grade: "))
class_name = input("Enter class: ")
student = Student(name, grade, class_name)
students.append(student)
print("Student details added successfully!")
print()
return students
| true |
4119618de10267b55678d20df8b09a0e815be097 | Veasba/Mi-primer-programa | /comer_helado.py | 854 | 4.21875 | 4 | quieres_helado_input = input("Quieres un helado? (si/no): ").upper()
if quieres_helado_input == "SI":
quieres_helado = True
elif quieres_helado_input == "NO":
quieres_helado = False
else:
print("Te he dicho que me digas si o no, no se que me has dicho entonces contare que es un no")
quieres_helado = False
tienes_dinero_input = input("Tienes dinero para un helado? (si/no): ").upper()
esta_abierto_input = input("Esta el super abierto? (si/no): ").upper()
esta_tu_mama_input = input("Estas con tu madre? (si/no): ").upper()
tienes_dinero = tienes_dinero_input == "SI"
esta_tu_mama = esta_tu_mama_input == "SI"
puede_comprarlo = tienes_dinero or esta_tu_mama
esta_abierto = esta_abierto_input == "SI"
if quieres_helado and puede_comprarlo and esta_abierto:
print("Pues comete un helado")
else:
print("Pues no comas nada")
| false |
4e1e6d3ced20ca006c5181ecb1817e08ce74ac59 | vinodsubbanna/Python | /asmnt26.py | 285 | 4.21875 | 4 | # 26)Define a function that can receive two integral numbers in string form
# and compute their sum and then print it in console.
# Hints:
# Use int() to convert a string to integer.
def sumstring(a,b):
print(int(a)+int(b))
print(a+b)#String concatination
sumstring('5','10')
| true |
52c982ce4fb46cb8651d42134c0b448b4f874377 | vinodsubbanna/Python | /asmnt31.py | 401 | 4.375 | 4 | # 31)Define a function which can print a dictionary where the keys are
# numbers between 1 and 20 (both included) and the values are square of
# keys.
# Hints:
# Use dict[key]=value pattern to put entry into a dictionary.
# Use ** operator to get power of a number.
# Use range() for loops.
def square():
dict = {}
for i in range(1,21):
dict[i] = int(i)**2
print(dict)
square()
| true |
f18cb4f7b1f7fb535ca6d814a004d7b65a7dbd39 | vinodsubbanna/Python | /asmnt6.py | 914 | 4.15625 | 4 | # 6)Write a program that calculates and prints the value according to the
# given formula:
# Q = Square root of [(2 * C * D)/H]
# Following are the fixed values of C and H:
# c is 50,H is 30
# D is the variable whose values should be input to your program in a
# comma-separated sequence.
# Example
# Let us assume the following comma separated input sequence is given to
# the program:
# 100,150,180
# The output of the program should be:
# 18,22,24
# Hints:
# If the output received is in decimal form, it should be rounded off to
# its nearest value (for example, if the output received is 26.0, it should
# be printed as 26)
# In case of input data being supplied to the question, it should be
# assumed to be a console input.
import math
c = 50
h = 30
d = input("Enter the comma seperated values : ").split(",")
#d = inp.split(",")
for i in d:
val = int(math.sqrt((2*c*int(i))/h))
print(val,end=",")
| true |
a3ef753016a598efbac9109f2862aefe0856cc82 | doctorchen03/basic-concept | /[1]/[1]/tuple.py | 484 | 4.40625 | 4 | #A tuple is a collection which is ordered and unchangeable
#initialize
tuple1 = ('a','b','c')
print(tuple1)
#get the list data type.
print(type(tuple1))
print(tuple1[0])
#tuple1[0] = 'A' #throw error, value assignment isn't allowed.
#print(tuple1)
#loop through the tuple
for i in range(0,len(tuple1)):
print(tuple1[i])
#delete the specified item.
#del tuple1[0] #throw error, value deletion isn't allowed.
del tuple1 #still, the whole tuple object can be removed.
#print(tuple1) | true |
c29f54574ef99116e9aa4176ca786336b9b923c0 | kakashihatakae/PreCourse_2 | /Exercise_4.py | 1,209 | 4.53125 | 5 | # Python program for implementation of MergeSort
def mergeSort(arr):
#write your code here
if len(arr) <= 1 :
return arr
if arr:
left = 0
right = len(arr)
mid = (left+right)//2
first = mergeSort(arr[left:mid])
second = mergeSort(arr[mid:right])
new_arr = [0]*len(arr)
one = two = ptr = 0
# print(first, second)
while one < len(first) and two < len(second):
if first[one] <= second[two]:
new_arr[ptr] = first[one]
one += 1
ptr += 1
elif second[two] < first[one]:
new_arr[ptr] = second[two]
two += 1
ptr += 1
if one < len(first):
new_arr[ptr:] = first[one:].copy()
elif two < len(second):
new_arr[ptr:] = second[two:].copy()
# print(new_arr)
# print('---')
return new_arr
# Code to print the list
def printList(arr):
print(arr)
#write your code here
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
arr = [9,8,7,6,5,4,3,2,1]
print ("Given array is", end="\n")
printList(arr)
sorted_array = mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(sorted_array)
| false |
7bf51504d9050e7d0d7959ae823a8eada340a239 | Neeraj-kaushik/Geeksforgeeks | /Array/Third_Largest_Element.py | 211 | 4.21875 | 4 | def third_largest_element(li):
if len(li) < 3:
print('-1')
else:
li = sorted(li)
print(li[-3])
n = int(input())
li = [int(x) for x in input().split()]
third_largest_element(li)
| false |
cd37cffd697ce9ff0abb7a59a646a44c4c3deceb | Someshshakya/CodeChef | /nav_26.py | 249 | 4.125 | 4 | ''' Draw a flow chart to print numbers from N to 1, where N is given as an input from the user.
Sample Input:
5
Sample Output:
5
4
3
2
1
'''
n = int(input("Enter your number to print nubers to 1:- "))
for i in range(n,0,-1):
print(i) | true |
09f3a0c0a3f802b2bda11613dbf2d6615a40a240 | Someshshakya/CodeChef | /nav_16.py | 681 | 4.1875 | 4 | '''Write the program to check NAVHW_014 then print NAVHW_015.
'''
a = int(input("Enter the angle of the Triangle: "))
b = int(input("Enter the angle of the Triangle: "))
c = int(input("Enter the angle of the Triangle: "))
if a!=0 and b!=0 and c!=0:
if (a+b+c == 180):
if (a == 90 or b==90 or c==90):
print('This is angle is right angled Triangle')
else:
if (a < 90 and b<90 and c<90):
print("This is an Acute angled Triangle")
else:
print("This is an Obtuse angled Triangle")
else:
print("NO it is not possible to form !")
else:
print("The tringle is not able is form ! ") | true |
a5e1f97a36159cb9baa70e66395c01255814130f | Someshshakya/CodeChef | /nav_56.py | 392 | 4.125 | 4 | '''NAVHW_056: Given a list [‘a’, 1, ‘2’, 5, ‘b’, ‘q’]. Print the last ‘N’
elements of the given list. ‘N’ is accepted from the user.
Input:
1
Output:
q
Input:
3
Output:
5
b
q
'''
my_list = ["a","c",3,"n","k",4]
n = int(input("Enter the number:- "))
# to print the elements from the list till the last
for index in range(n,0,-1):
print(my_list[index*(-1)]) | true |
6d203fc30fc9361711a524c45cc2336d7197edeb | Someshshakya/CodeChef | /nav_53.py | 547 | 4.375 | 4 | '''
NAVHW_053: Draw a flowchart to take an input N and print the following sequence.
Sample input
5
Sample Output
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
'''
n = int(input("Enter your number to form the pattern-: "))
count = 1
d = 1
while count<= n:
# to print the pattern in increasing order
m = count
while m<d:
print(m,end=" ")
m+=1
# to print the pattern in reverse order after reaching the n number
while m>=count:
print(m,end=" ")
m-=1
print()
count +=1
d += 2 | true |
45fc16b703b48ebb00c2b2dfa913ef5d3b8bc9a5 | Someshshakya/CodeChef | /nav_31.py | 371 | 4.3125 | 4 | '''NAVHW_031:: Draw a flowchart to input a number and check if its second last digit is 7 or not.
Sample Input:
276
Sample output:
Yes
'''
n = int(input("enter a number "))
mod = (n%100)//10 # Here you will get the last digit
if mod == 7:
print("yes 7 is the 2nd last digit of a number ",mod)
else:
print("no 7 is not the 2nd last digit of a number ",mod)
| true |
41aa1c56f13b873c62fd5c6cc27a98c0b08e1d5e | Someshshakya/CodeChef | /nav_32.py | 227 | 4.25 | 4 | '''
NAVHW_032:: Draw a flowchart to input a number, print all of its factors.
Sample Input:
5
Sample Output:
1
5
Sample Input:
6
Sample Output
1
2
3
6
'''
n = int(input())
for i in range(1,n+1):
if n%i==0:
print(i) | true |
b9bfa605cdd406395420168f1cf147c3d8ee339f | sumitvarun/pythonprograms | /using sort()andreverse().py | 226 | 4.34375 | 4 | #using sort() and reverse() method
List= ["Book","Apple","Dog","Camel"]
#List.sort(reverse= True)
#We can sort this list from the End.or from the right to the left by using reverse() method.
List.reverse()
print(List)
| true |
39bc5205f5228c8ca814cb9d775e7cffb812fc54 | sammymuriuki/pythonloops | /c_name_variables.py | 2,064 | 4.75 | 5 | """
STEP THREE
Now that we can print each member, let's try printing just each member's name and phone number.
We'll need to extract the details if we want to print demand letters.
Steps:
* Copy and paste the code from the previous step.
* Modify it here so instead of printing the entire list of facts about each member inside your for loop, you extract
each fact into a separate variable that indicates its meaning, such as
`name`, `phone_number`, `address`, `city`, `state`, `zip_code`, and `purchases`.
* Print just the name and phone number for each member.
* As usual, add comments before each block of code to explain what each block does.
(Why include this step? We *could* just refer to member[0] the entire time instead of using a new variable like "name".
But programming is easier if you move data around into variables that make sense to you.)
"""
import json
members_file = open('member_info.json')
members = json.load(members_file)
members_file.close()
""" iterate over the members list. each member is assigned to a variable called `member' """
for member in members:
""" assign the first element of the member variable (index 0) to variable `name`"""
name = member[0]
""" assign the second element of the member variable (index 1) to variable `phone_number`"""
phone_number = member[1]
""" assign the third element of the member variable (index 2) to variable `address`"""
address = member[2]
""" assign the fourth element of the member variable (index 3) to variable `city`"""
city = member[3]
""" assign the fifth element of the member variable (index 4) to variable `state`"""
state = member[4]
""" assign the sixth element of the member variable (index 5) to variable `zip_code`"""
zip_code = member[5]
""" assign the seventh element of the member variable (index 6) to variable `purchases`"""
purchases = member[6]
""" print the value of the variable `name`"""
print(name)
""" print the value of the variable `phone_number`"""
print(phone_number)
| true |
95df8a752507ed92d9e064a3ba49c8cbddb97cdc | Raeebikash/python_class1 | /python_class/exerci7.py | 709 | 4.21875 | 4 | #exercise, number geussing game
#make a variable , like winning_number and assign any number to it.
#ask user to geuss a number.
#if user geussed correctly then print "you win!!"
#if user didn"t guessed correctly then:
#if user geussed lower than actual number then print "too low"
#if user geussed higher than actual number then print "too high"
#google "how to generate random number in python "to generate random
#winning number
winning_number = 55
user_input = input("geuss a number between 1 to 100:")
user_input = int(user_input)
if user_input == winning_number:
print("YOU WIN!!!")
else:
if user_input <winning_number:
print("too low")
else:
print("too high")
| false |
94ac248f2b980a6eb92196af0e7f72b08f98e7d5 | blicogam/pythonExe | /ch1num1.py | 415 | 4.34375 | 4 | import math
import fractions
def main():
userInput = input("Enter radius: ")
try:
radius = float(userInput)
diameter = radius * 2.0
circum = diameter * math.pi
sa = circum * 2.0 * radius
vol = sa * radius * fractions.Fraction('1/3')
print(radius)
print(diameter)
print(circum)
print(sa)
print(vol)
except ValueError:
print("Invalid radius:",userInput )
if __name__ == '__main__':
main() | false |
3f086a6b5ace65a87fb26f53c88e871519a201af | martimartins/Roman-numerals-converter | /main.py | 2,442 | 4.125 | 4 | numeros_rumanos = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L" : 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1,
}
def ConvertNumberRoman(value: int) -> str:
"""
Função para converter numero inteiros para numeros romanos usando dict(numeros_rumanos),
ele verifica cada item da dict e vê se o valor do item é menor que o number_remening(value),
se sim ele adiciona a str roman_number e diminui pelo valor do item.
"""
roman_number = ""
number_remening = int(value)
count = 0
# VER TODO O DICIONARIO numeros_rumanos
for num in list(numeros_rumanos):
# VERIFICA SE O VALOR DO ITEM É MENOR OU IGUAL AO NUMBER_REMENING(VALUE)
while int(numeros_rumanos[num]) <= int(number_remening):
# ADICIONAR O VALOR DO ITEM (Exemple: X;V;I) A STR roman_number
if num == "M":
count += 1
roman_number += num
# DIMINUIR AO VALOR TOTAL DO NUMERO PEDIDO EM ROMAN
number_remening -= int(numeros_rumanos[num])
# RETURNAR O VALOR FINAL (o valor romano)
if count > 1:
roman_number = roman_number.replace("M"*count, "M*"+str(count)+" ")
return str(roman_number)
def ConverterRomanNumber(value: str) -> str:
"""
Função para converter numeros rumanos em numeros inteiros usando dict(numeros_rumanos),
ele vericia cada item na dict, e verifica se existe no value(valor inserido pelo usuario).
"""
total_number = 0
index_position = 0
# VER TODO O DICIONARIO numeros_rumanos
for num in list(numeros_rumanos):
# VERIFICAR SE O item DO DICIONARIO TEM NO VALUE(input)
while str(num) == value[index_position:index_position+len(num)]:
# ADICIONAR PELO DICIONARIO O VALOR DA LETRA ROMANA (Exemple: X: 10)
total_number += numeros_rumanos[num]
# ADICIONAR O NUMERO DE CARACTERES QUE O NUMERO ROMANO TINHA, PARA O WHILE NÃO VERIFICAR SEMPRE A MESMA LETRA
index_position += len(num)
# RETURNAR O VALOR FINAL
return str(total_number)
def main() -> None:
print("Convertor de numeros rumanos\n\n")
value = input(">> ")
try:
int(value)
print("\n/*= "+ConvertNumberRoman(value))
except:
print("\n/*= "+ConverterRomanNumber(value))
try:
main()
except KeyboardInterrupt:
print("\rAdeus!")
| false |
846e6377f91aef16d7c47d0cbdfe0b9586b6d934 | antjowie/Python-exercises | /33_birthday_dictionaries.py | 543 | 4.5625 | 5 | birthdays = {
'James Franklin' : '07/11/1995',
'Howard Jobson' : '14/03/1982',
'Anderson Stevens' : '07/13/1975'
}
print('Welcome to the birthday dictionary. We know the birthdays of:','\n'.join(birthdays.keys()),'Who\'s birthday do you want to look up?', sep='\n')
# Convert all first cases to upper cases
name = input().capitalize()
name = [string.capitalize() for string in name.split()]
name = ' '.join(name)
if name not in birthdays:
print('We do not have any record of the name',name)
else:
print(f"{name}'s birthday is {birthdays[name]}") | true |
346fd7631d3521c05ae8911e1a29a88dc8d0e408 | antjowie/Python-exercises | /09_guessing_game_one.py | 1,038 | 4.125 | 4 | import random
def main():
print('Welcome to the guess game')
while True:
# Generate a random number and setting up game related vars
rand = random.randint(1, 9)
count = 1
print('A number between 1 and 9 has been generated')
while True:
# Validate guess
guess = input("Your guess " + str(count) + ': ')
if guess.isnumeric() == False:
print('Your guess should be an integer')
continue
# Check input
guess = int(guess)
if guess == rand:
print('Correct!, it took you', count, 'attempts to guess right')
break
elif guess > rand:
print('Your guess is too high')
elif guess < rand:
print('Your guess is too low')
count += 1
if str(input('Type exit if you want to quit or nothing to keep on playing ')).lower() == 'exit':
break
if __name__ == '__main__':
main()
| true |
0a497ca2bb9d8f6cd035735fd5df0f3d0d45d909 | antjowie/Python-exercises | /15_reverse_word_order.py | 219 | 4.375 | 4 | def reverse(string):
# reversed_words = string[::-1].split()
# return (' '.join([a[::-1] for a in reversed_words]))
return ' '.join(string.split()[::-1])
string = 'My name is Michele'
print(reverse(string)) | false |
e05c3355245aa3dd53dbaf7f10a0442643ae5073 | khanmaster/python_string_casting | /loops.py | 1,201 | 4.5625 | 5 | # # what are loops
# # for loops are used to iterate through Lists, strings, Dictionaries and Tuples
# # syntax:- for variable in name of the data_collection(list,string,dictionary or Tuple)
#
#
# list_data = [1, 2, 3, 4, 5]
# for data in list_data:
#
# # if condition will come inside for loop
# if data > 4:
# print(data)
# # break condition will come inside if block
# #print(data)
# # print data block should be within if block
# create a string and loop through the string
# city = "London"
# for letter in city:
# print(letter)
# print the string in one line
# looping through a dictionary
student_record = { "name": "shahrukh",
"stream": "DevOps",
"completed_lesson": 5,
"completed_lessons_names": ["strings", "Tuples", "variables"]
}
for record in student_record.keys():
if record == "name":
print(record)
elif record == 5:
print(record)
# exercise
# dictionary with employee records minimum 5 key value pairs
# using loop iterate through the dictionary
# display the values of and keys of the dictionary
#
# print(list_data[0])
# print(list_data[1])
# print(list_data[2])
| true |
976258d606c94b394f496f6918c94282452abfae | phyllsmoyo/Python | /python object oriented programming/Ex_Files_Python_Object_Programming/Ex_Files_Python_Object_Programming/Exercise Files/Ch 4/datadefault_start.py | 551 | 4.28125 | 4 | # Python Object Oriented Programming by Joe Marini course example
# implementing default values in data classes
from dataclasses import dataclass, field
import random
def price_func():
return float(random.randrange(20, 40))
@dataclass
class Book:
# you can define default values when attributes are declared
title: str = "No Title"
author: str = "No Autor"
pages: int = 0
price: float = field(default_factory=price_func)
b1 = Book("Umzilakawulandelwa", "NS Sigogo", 235)
b2 = Book("Umzilaka", "NS ", 300)
print(b1)
print(b2) | false |
a88582cb9ee239cec24c4971435ccd799906b3f8 | tommyreins/codingtutorial | /Logan's Program Practice/Guess the Number/Guess the Number v1.py | 1,610 | 4.40625 | 4 | #The goal of creating this is to create a program that will...
#...randomly generate a number, then tell you higher or lower after a guess until you guess it.
#I looked online on how to generate random numbers and it sent me to the "import random"
#After researching the import command for more info i found that it will call in another module...
#...python has modules built into it for basic uses such as the "sys" i have seen, as well as "random"
import random
#I believe "randint" is a function in the module and "random.randint()" searches for that spcific function in it
#"random.randint(x,y)" will choose a random number between two values x and y
randomint = random.randint(1,21)
print('Guess a number between 1 and 20.')
#This is a loop to see if the users input is the same, and to say if it is higher or lower, then guess again
while True : # this sets the loop to run forever because "while" runs as long as it evaluates to true, and by saying "True" it means it will evaluate to true
guess = int(input()) #the variable "guess" is being set equal to the users input, then being turned into an integer
if guess == randomint : #when the users input is equal to the random number
print('You guessed it!') # then print this
break # and stop the loop
elif guess < randomint : #if the user input is less than the random number
print('Higher!') #then tell me to guess higher and return me to the top of the loop
elif guess > randomint : # if guess is greater than the number
print('Lower!') #then tell me to guess lower and return to the top
| true |
1ca82b31b1fd5773c951ddf0346c2744a4f65526 | ripley57/CW_Tools | /tools/python/class_demos/class_property_decorator.py | 695 | 4.21875 | 4 | # Note: You must run this with python3
# The '@property' annotation can be used to create a "getter()" method.
# Note that below we cal 't.temp' and not 't.temp()'.
# The '@xxx.setter' annotation can be used to create a "setter()" method.
class Temperature:
def __init__(self):
self._temp_fahr = 0
@property
def temp(self):
print("getter called")
return (self._temp_fahr - 32) * 5 / 9.0
@temp.setter
def temp(self, new_temp):
print("setter called")
self._temp_fahr = new_temp * 9 / 5 + 32
t = Temperature()
# direct access
#print(t._temp_fahr)
# use the getter
print(t.temp)
# use the setter
t.temp = 34
# direct access
#print(t._temp_fahr)
# getter again
print(t.temp)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.