blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9b9e0bd9b4787a24bfc333e1f440ee144073f4bf | tabish606/python | /identity_matrix.py | 645 | 4.15625 | 4 | #print identity matrix for example
# 1 0 0
# 0 1 0
# 0 0 1
m = int(input('enter the order of matrix : '))
#list comprehension
#mat = [[] for i in range (0,m)]
#mat = [[0 for j in range(0,m) for i in range(0,m)]]
#mat = [[int(input()) for i in range(0,m)] for i in range(0,m)]
mat = []
for i in range(0,m):
mat.append([])
for i in range (0,m):
for j in range(0,m):
mat[i].append(j)
mat[i][j] = 0
for i in range(0,m):
for j in range(0,m):
if (i == j):
mat[i][j] = 1
print(mat[i][j] ,end = " ")
print("\n")
| false |
7d6b7ba3ac0bf3ee292dfa0178f6414549ececb3 | ycw786369470/PythonTest | /算法/快速排序/快排.py | 885 | 4.15625 | 4 |
def quick_sort(list1, left, right):
#左右下标
if left >= right:
return None
n = left
m = right
#基准值
base = list1[n]
while n < m:
#从右边往左边找一个比base小的
while list1[m]>=base and n < m:
m -= 1
if n == m:
list1[n] = base
else:
#拿小的值填前面的坑
list1[n] = list1[m]
#从左边往右边找一个比base大的
while list1[n]<=base and n < m:
n += 1
if n == m:
list1[n] = base
else:
list1[m] = list1[n]
#对左边的进行快排
quick_sort(list1, left, n-1)
#对右边的进行快排
quick_sort(list1, n+1, right)
if __name__ == '__main__':
list1 = [30, 5, 4, 13, 15, 9, 20, 17, 40, 31]
quick_sort(list1, 0, len(list1) - 1)
print(list1) | false |
0384000aaaedfd61cf915234cc419e4d9deff281 | kadamsagar039/pythonPrograms | /pythonProgramming/bridgelabzNewProject/calender.py | 653 | 4.15625 | 4 | """Calender Program
This program is used to take month and year from user and print corresponding Calender
Author:
Sagar<kadamsagar039@gmail.com>
Since:
31 DEC,2018
"""
from ds_utilities.data_structure_util import Logic
def calender_runner():
"""
This method act as runner for calender_queue(month, year)
:return: nothing
"""
logic_obj = Logic()
try:
month = int(input('Enter month: '))
except:
print("Enter integer only ")
try:
year = int(input("Enter Year: "))
except:
print("Enter integer only")
logic_obj.calender(month, year)
if __name__ == "__main__":
calender_runner()
| true |
d389e3a7ad0bd05f8ec5f50d0c9b3d192859f41a | StudentDevs/examples | /week1/2.py | 1,958 | 4.8125 | 5 | """
Tutorials on sqlite (quickly grabbed off google, there may be better ones):
https://stackabuse.com/a-sqlite-tutorial-with-python/
https://pynative.com/python-sqlite/
"""
import sqlite3
def main():
print('Connecting')
conn = sqlite3.connect(':memory:')
# Configure the connection so we can use the result records as dictionaries.
conn.row_factory = sqlite3.Row
# Get a "cursor" for database operations.
cur = conn.cursor()
print('Creating table')
sql = '''CREATE TABLE people (
id integer PRIMARY KEY,
first_name text NOT NULL,
last_name text NOT NULL)'''
cur.execute(sql)
print('Selecting all')
cur.execute('SELECT * FROM people')
for i in cur.fetchall():
print(dict(i))
print('Inserting')
cur.execute('INSERT INTO people (id, first_name, last_name) VALUES (1, "joe", "aaa")')
cur.execute('INSERT INTO people (id, first_name, last_name) VALUES (2, "jane", "bbb")')
cur.execute('INSERT INTO people (id, first_name, last_name) VALUES (3, "marty", "ccc")')
print('Selecting all')
cur.execute('SELECT * FROM people')
for i in cur.fetchall():
print(dict(i))
print('Selecting all and printing only specific columns')
cur.execute('SELECT * FROM people')
for i in cur.fetchall():
print('first: {} / last: {}'.format(i['first_name'], i['last_name']))
print('Selecting id 3')
cur.execute('SELECT first_name, last_name FROM people WHERE id = 3')
result = cur.fetchone()
if result:
print(dict(result))
else:
print('No record found')
print('Deleting id 3')
cur.execute('DELETE FROM people WHERE id = 3')
print('Selecting id 3')
cur.execute('SELECT first_name, last_name FROM people WHERE id = 3')
result = cur.fetchone()
if result:
print(dict(result))
else:
print('No record found')
if __name__ == '__main__':
main()
| true |
a268b45504f17b58cdf3e5537a47f68ec6e9faa3 | 3NCRY9T3R/H4CKT0B3RF3ST | /Programs/Python/bellman_ford.py | 1,438 | 4.1875 | 4 | #This function utilizes Bellman-Ford's algorithm to find the shortest path from the chosen vertex to the others.
def bellman_ford(matrix, nRows, nVertex):
vertex = nVertex - 1
listDist = []
estimation = float("inf")
for i in range(nRows):
if (i == vertex):
listDist.append(0)
else:
listDist.append(estimation)
for i in range(nRows-1):
for j in range(nRows):
for k in range (nRows):
if (matrix[j][k] != 0 and matrix[j][k] + listDist[j] < listDist[k]):
listDist[k] = matrix[j][k] + listDist[j]
return listDist
# This function prints the distance from the inital vertex to the othersdef printBF(lista):
def printBF(list):
nDist = len(list)
for i in range(nDist):
print("The distance to the vertex " + str(i + 1) + " is: " + str(list[i]))
#We start with the adjacency matrix of a weighted graph.
adjacencyMatrix = [[0, 10, 5, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 3, 0, 8, 2, 0], [0, 0, 0, 0, 4, 4], [0, 0, 0, 0, 0, 6], [0, 0, 0, 0, 0, 0]]
originVertex = 1 # Here you can chose the origin vertex (value >=1)
nRows=len(adjacencyMatrix[0])
nColumns=len(adjacencyMatrix)
#Here we get the shortest paths from the origin vertex utilizing Bellman-Ford's Algorithm
finalBF = bellman_ford(adjacencyMatrix, nRows, originVertex)
# Now we just print the distances from the chosen vertex to another.
printBF(finalBF)
| true |
442271b97e0a30d58c9e2a03a58a6e119112524a | jefflike/python_advance | /packet/006.鸭子类型与多态.py | 2,597 | 4.125 | 4 | '''
__title__ = '006.鸭子类型与多态.py'
__author__ = 'Jeffd'
__time__ = '4/14/18 4:39 PM'
'''
'''
tips:鸭子类型就是,当看到一只鸟走起来像鸭子,游泳像鸭子,叫起来也像鸭子
那么这只鸟就可以称作鸭子
python的多态性就是基于鸭子类型的
'''
# 在python中具有同样的方法的类我们可以把他归并成一类事物
class turtle:
def swim(self):
print('turtle swimming')
class duck:
def swim(self):
print('duck swimming')
class goose:
def swim(self):
print('goose swimming')
class swim_pig:
def swim(self):
print('swim_pig swimming')
# 这几个动物都具有相同的方法,即都会游泳,那么我们可以把他看作一类
fish = duck
fish().swim() # duck swimming
# 如果我根据他们都会游泳把他叫做鱼类型,这就是鸭子类型
# 通过魔法函数,对象可以72变,比如本来是鸡,但是通过定义魔法函数,就变成了鸭子
'''
面向对象的java实现鸭子类型是基于继承完成的
写一点java的伪代码
class fish:
def swim(self):
print('fish swimming')
class swim_pig(fish):
def swim(self):
print('swim_pig swimming')
fish sw = swim_pig()
sw.swim()
结果就是swim_pig swimming
'''
# python与java不同的地方就在于,我们不需要静态指明类型
# sw不必须指定为fish类型,python语言本身就自带多态性的
fish_list = [turtle, duck, goose, swim_pig]
# 我们把这些都具有游泳方法的类归并为fish_list,即鱼一类
for fish in fish_list:
fish().swim()
# 这种多态思维是构建python语法的基础
'''
python的多态性,是贯穿整个语言的,比如我们根据python的自定义类型可以将
python的类型进行划分,比如我们对具有__iter__方法的对象,我们就称他为可迭代
对象,那么对于这类方法我们可以对他们进行各种的迭代操作,具有__iter__方法的类
我们就根据这个特征将他们归并为一类。
def extend(self, iterable): # real signature unknown; restored from __doc__
""" L.extend(iterable) -> None -- extend list by appending elements from the iterable """
pass
举例子:
上面是[]的扩展方法,[].extend()方法传人的参数不仅仅是列表类,而是所有实现了
__iter__方法的类,即所有可迭代对象都可以作为参数传入,这种思想贯穿了我们的python,
python的魔法类型就是基于此使用,才使得python如此灵活
'''
| false |
8b8177c2acb317808a8e4808293cdc8b690f230f | NirajPatel07/Algorithms-Python | /insertionSort.py | 376 | 4.125 | 4 | def insertionSort(list1):
for i in range(1,len(list1)):
curr=list1[i]
pos=i
while curr<=list1[pos-1] and pos>0:
list1[pos]=list1[pos-1]
pos-=1
list1[pos]=curr
list1=list(map(int, input("Enter Elements:\n").split()))
print("Before Sorting:\n",list1)
insertionSort(list1)
print("After Sorting:\n",list1)
| true |
2a575b03af1d4347b73917510fd275583fa674c3 | GrandPa300/Coursera-RiceU-Python | /01_Rock-paper-scissors-lizard-Spock/Rock-paper-scissors-lizard-Spock.py | 2,074 | 4.15625 | 4 | # Mini Project 1
# Rock-paper-scissors-lizard-Spock
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
import random
def number_to_name(number):
# fill in your code below
if number == 0:
name = "rock"
elif number == 1:
name = "Spock"
elif number == 2:
name = "paper"
elif number == 3:
name = "lizard"
elif number == 4:
name = "scissors"
return name
# convert number to a name using if/elfi/else
#don't forget to return the reslut!
def name_to_number(name):
# fill in your code below
if name == "rock":
number = 0
elif name == "Spock":
number = 1
elif name == "paper":
number = 2
elif name == "lizard":
number = 3
elif name == "scissors":
number = 4
return number
# convert number to a name using if/elfi/else
#don't forget to return the reslut!
def rpsls(name):
# fill in your code below
player_number = name_to_number(name)
comp_number = random.randrange(4)
print "Player chooses " + name
print "Computer chooses " + number_to_name(comp_number)
difference = (player_number - comp_number)%5
#print player_number
#print comp_number
#print difference
print "=============="
if difference > 2:
print "Computer wins!"
elif difference == 0:
print "Player and Computer ties!"
else:
print "Player wins!"
print "=============="
print ""
# convert name to player_number using name_to_number
# compute random guess for comp_number using random.randrange()
# compute difference of player_number and comp_number modulo five
# use if/elif/else to determine winner
# convert comp_number to name using number_to_name
# print results
# test your code
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors") | true |
66dca308dded21abc0509cd24802891564c63c0d | Taylorsuk/Game-of-Hangman | /hangman.py | 2,950 | 4.125 | 4 | import random
import re
# import the wordlist
txtfile = open('word_list.txt', 'r')
wordsToGuess = txtfile.readlines()
allowedGuesses = 7
incorrectGuesses = []
correctGuesses = []
randomWord = random.choice(wordsToGuess).strip()
guessWord = []
maskCharacter = '*'
# we have a random word so we can now start the game
print("Lets play a game of Hangman")
for character in randomWord:
guessWord.append(maskCharacter)
print("The word you are trying to guess is {}".format(''.join(guessWord)))
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
# while they still have guesses in the bank run this loop
while allowedGuesses - len(incorrectGuesses) > 0:
# get an input from the user
letterGuess = input('\n\nGuess a letter: ').lower()
# check that its a valid letter (and they actually entered something!)
if not re.match("^[a-z]*$", letterGuess):
print('You can only enter a character from the alphabet (a - z)')
continue
elif len(letterGuess) > 1 or len(letterGuess) == 0:
print("You must enter a single character")
print(letterGuess)
continue
# already tried the letter
elif (letterGuess in correctGuesses) or (letterGuess in incorrectGuesses):
print("You have already tried {}. Please enter your next guess: {}".format(letterGuess, ''.join(guessWord)))
continue
# letter is in the word
# letterIndex = randomWord.find(letterGuess)
letterIndices = findOccurrences(randomWord, letterGuess)
# if letterIndex >= 0:
if len(letterIndices) > 0:
correctGuesses.append(letterGuess)
print('awesome guess, "{}" is in the word.'.format(letterGuess))
for letterIndex in letterIndices:
guessWord[letterIndex] = letterGuess
# incorrect guess
else:
# push the incorrect guess to the incorrect guess list and
incorrectGuesses.append(letterGuess)
# calculate the guesses remaining
remaining = allowedGuesses - len(incorrectGuesses)
# notify the user
print("Sorry, you lose a life, '{}' is not in the secret word, {} guesses remaining. \n\n Please enter your next guess: {}".format(
letterGuess, remaining, ''.join(guessWord)))
# check if that was their last life
if remaining == 0:
print('Sorry, you failed to guess the word: "{}", you lose, why not give it another go!'.format(randomWord))
break
print('Incorrect guesses: "{}"'.format(incorrectGuesses))
# show current status
print('Please enter your next guess: {}'.format(''.join(guessWord)))
# let's see how many remaining stars there are:
remainingStars = findOccurrences(guessWord, maskCharacter)
# they have guessed all the letters Winner!
# if len(correctGuesses) == len(randomWord):
if len(remainingStars) == 0:
print('Congratulations you win')
break
| true |
78182f8b7eeed49d51da5ad194732dbee021ddf4 | aiqingr/python-lesson | /pythonProject/python1/inputExample.py | 319 | 4.21875 | 4 | # num_input = input("Input a number")
# print(num_input ** 2)
# First two line will popup an error because the input function always return a string
# This will be Method One
# num_input_1 = input("input a number: ")
# print(int(num_input_1) ** 2)
num_input_2 = int(input("input a number: "))
print(num_input_2 ** 2)
| true |
41aed98b579dcc9e7621c9356685aacc33fcf7e9 | fivaladez/Learning-Python | /EJ10_P2_Classes.py | 981 | 4.28125 | 4 | # EJ10_P2 Object Oriented - Classes
# Create a class
class exampleClass:
eyes = "Blue"
age = 22
# The first parameter MUST be self to refers to the object using this class
def thisMethod(self):
return "Hey this method worked"
# This is called an Object
# Assign the class to an a variable to the class
exampleObject = exampleClass()
# Calling methods from our Object
# Members from our class
print " ", exampleObject.eyes
print " ", exampleObject.age
print " ", exampleObject.thisMethod()
class className:
def createName(self, name):
# Create a var called name and assign the parameter name
# This is because the variable is inside a function
self.name = name
def displayName(self):
return self.name
def saying(self):
print " Hello %s" % self.name
first = className()
second = className()
first.createName("Ivan")
print " ", first.displayName()
first.saying()
print " ", first.name
| true |
ebbdc407c8e93e02618d8aec68213b2229de61ec | fivaladez/Learning-Python | /EJ21_P2_Lambda.py | 1,006 | 4.375 | 4 | # EJ21_P2 Lambda expression - Anonymous functions
# Write function to compute 3x+1
def f(x):
return 3*x + 1
print f(2)
# lambda input1, input2, ..., inputx: return expression in one line
print lambda x: 3*x + 1
# With the above declaration we still can not use the function,
# we need a name, so, we can do the next thing:
def g(x): return 3*x + 1
print g(2)
def full_name(fn, ln): return fn.strip().title()+" " + ln.strip().title()
print full_name("Ivan ", "Valadez ")
soccer_players = ["Leonel Messi", "Cristiano Ronaldo", "Ricardo Kaka"]
print soccer_players
# in sort method, take each of the spaces from a list (one by one)
soccer_players.sort(key=lambda name: name.split(" ")[-1].lower())
print soccer_players
# Function to create functions
def build_quadratic_function(a, b, c):
"""Returns the function f(x) = ax^2 + bx + c"""
return lambda x: a*x**2 + b*x + c
# Option 1
f = build_quadratic_function(2, 3, -5)
print f(0), f(1), f(2)
# Option 2
print build_quadratic_function(2, 3, -5)(2)
| true |
99002d0f430011ee9f40ac32feac98b84b435544 | fivaladez/Learning-Python | /EJ11_P2_SubClasses_SuperClasses.py | 1,065 | 4.40625 | 4 | # EJ11_P2 Object Oriented - subClasses and superClasses
# SuperClass
class parentClasss:
var1 = "This is var1"
var2 = "This is var2 in parentClass"
# SubClass
class childClass(parentClasss):
# Overwrite this var in this class
var2 = "This is var2 in childClass"
myObject1 = parentClasss()
print " ", myObject1.var1
# You can acces to upper layer class "parentClasss"
myObject2 = childClass()
print " ", myObject2.var1
print " ", myObject1.var2
print " ", myObject2.var2
# ==================================================
# Multiple inhertance
class mom:
mom = "Im mom"
class dad:
dad = "Im dad"
# child class inherit/hereda the elements of classes mom and dad
class son(mom, dad):
son = "Im son"
myObject3 = son()
print " ", myObject3.mom
print " ", myObject3.dad
print " ", myObject3.son
# ==================================================
# Constructor
class new:
def __init__(self):
print " This is the contructor of class new: "
# Automatically calls the constructor
myObject4 = new()
| true |
3194e6d5a08128b1eb943b29f579bf3bf72b1d68 | tanish522/python-coding-prac | /stack/stack_1.py | 415 | 4.15625 | 4 | # stack using deque
from collections import deque
stack = deque()
# append() function to push element in the stack
stack.append("1")
stack.append("2")
stack.append("3")
print('Initial stack:')
print(stack)
# pop() fucntion to pop element
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack) | true |
2e1f82907b455f15ddaa77b4a3841c2dd61f6de5 | ArsenArsen/claw | /claw/interpreter/commands/cmd_sass.py | 1,764 | 4.125 | 4 | """
Takes the given input and output directories and compiles all SASS files in the input into the output directory
The command takes three parameters, namely target, directory, and glob:
sass <source> <target> [style]
The source parameter is relative to the claw resource directory
The target parameter is where the compiled files will reside
The style argument is the style of the output.
It is assumed that the source is a directory unless it's found that it is a file
See: https://sass.github.io/libsass-python/sass.html#sass.compile
For example, to compile all sass files in scss and put them in static, as compacted css files:
sass scss static compact
To take index.scss and compile it into static/index.css:
sass index.scss static/index.css
"""
from os.path import join, isfile, exists, dirname
from os import makedirs
from claw.errors import ClawParserError, check_deps
check_deps("SASS compiler", "sass")
import sass
def claw_exec(claw, argv):
# pylint: disable=missing-docstring
if len(argv) != 3 and len(argv) != 4:
raise ClawParserError("sass requires two or three arguments")
src = join(claw.resource_dir, argv[1])
dst = join(claw.output_dir, argv[2])
style = "nested" if len(argv) == 3 else argv[3]
if not exists(src):
raise ClawParserError("sass source: no such file or directory")
try:
if isfile(src):
makedirs(dirname(dst), exist_ok=True)
with open(dst, 'w') as target:
target.write(sass.compile(filename=src, output_style=style))
else:
sass.compile(dirname=(src, dst), output_style=style)
except sass.CompileError as error:
raise ClawParserError("There was an error while compiling sass files:", error)
| true |
649df4c7b9f19ab38d3924cd2dc68f956b70f90b | iEuler/leetcode_learn | /q0282.py | 1,461 | 4.28125 | 4 | """
282. Expression Add Operators
https://leetcode.com/problems/expression-add-operators/
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
Example 1:
Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]
Example 2:
Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]
Example 3:
Input: num = "105", target = 5
Output: ["1*0+5","10-5"]
Example 4:
Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]
Example 5:
Input: num = "3456237490", target = 9191
Output: []
"""
from typing import List
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
def helper(s, k):
if k == 0:
if s[0] == '0' and len(s) > 1 and s[1] not in '+-*':
return []
return [s] if eval(s) == target else []
ans = helper(s, k - 1)
if s[k] != '0' or k == len(s)-1 or s[k+1] in '+-*':
ans += helper(s[:k] + '+' + s[k:], k - 1)\
+ helper(s[:k] + '-' + s[k:], k - 1)\
+ helper(s[:k] + '*' + s[k:], k - 1)
return ans
if not num:
return []
return helper(num, len(num)-1)
num = "105"
target = 5
num = "123"
target = 6
num = "00"
target = 0
num = ""
target = 5
print(Solution().addOperators(num,target)) | true |
444ef66071c458cf92cfff248f813ab29608c91e | Prashant1099/Simple-Python-Programs | /Count the Number of Digits in a Number.py | 318 | 4.15625 | 4 | # The program takes the number and prints the number of digits in the number.
n = int(input("\nEnter any Number = "))
count = 0
temp = n
while (n>0):
n //= 10
count += 1
print("-----------------------------------")
print("Number of Digits in ",temp, " = ",count)
print("-----------------------------------") | true |
b8da10fe0d52d9d8ff08344c4bc8d3465b8f3e6d | atifahsan/project_euler | /p1.py | 275 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
numbers = [i for i in range(1, 1000) if not i % 3 or not i % 5]
print(sum(numbers)) | true |
1179247685bb98e5de3d5de793ba677670d18e55 | ananth-duggirala/Data-Structures-and-Algorithms | /Arrays and Strings/reverse_string.py | 338 | 4.28125 | 4 | """
Problem statement: Reverse a string.
"""
def reverseString(string):
newString = ""
n = len(string)
for i in range(n):
newString += string[n-1-i]
return newString
def main():
string = input("This program will reverse the entered string. \n\nEnter string: ")
print(reverseString(string))
if __name__ == "__main__":
main()
| true |
277cf603c8c3652936bc7f1ff1e6ded0111c82b0 | ClaudiaStrm/Introducao_ciencia_da_computacao | /04-01_fizzbuzz.py | 572 | 4.125 | 4 | #Escreva a função fizzbuzz que recebe como parâmetro um número inteiro e retorna
#'Fizz' se o número for divisível por 3 e não for divisível por 5;
#'Buzz' se o número for divisível por 5 e não for divisível por 3;
#'FizzBuzz' se o número for divisível por 3 e por 5;
#Caso a função não seja divisível 3 e também não seja divisível por 5, ela deve retornar o número recebido como parâmetro.
def fizzbuzz(x):
if x % 15 == 0:
resp = "FizzBuzz"
elif x % 3 == 0:
resp = "Fizz"
elif x % 5 == 0:
resp = "Buzz"
else:
resp = x
return resp
| false |
8391191aa5fc0ff6eb1d36d55e9105a6dc655c01 | kodfun/PythonOgreniyorum | /Strings5.py | 2,834 | 4.1875 | 4 | # STRING METOTLARI
# https://www.w3schools.com/python/python_strings_methods.asp
s = "merhaba DÜNYA"
print(s.capitalize())
print(s.upper())
print(s.lower())
print("01234567890123456789")
print("KODLUYORUM".center(20))
print("KODLUYORUM".center(20,"*"))
# KAÇ TANE A HARFİ GEÇİYOR?
s = "ankara"
print(s.count("a"))
# true ya da false döndürür
print(s.endswith("ra")) # ile biter mi
print(s.startswith("an")) # ile başlar mı
# sadece harf ve rakamdan mı oluşur
print("ankarağ123".isalnum()) # True
print("ankarağ123*".isalnum()) # False
# sadece harf mi
print("ankara".isalpha()) # True
print("ankara1".isalpha()) # False
# sadece sayılardan mı oluşuyor
print("a123".isnumeric()) # False
print("123".isnumeric()) # True
print("123.22".isnumeric()) # False
print("½11".isnumeric()) # True
# sadece rakamlardan mı oluşuyor
print("½11".isdigit()) # False
print("11".isdigit()) # True
# NOT: ½ bir sayısal (numeric) karakter iken kendisi bir rakam (digit) değildir.
s = "ANKARALI EVREN"
table = s.maketrans("AIE", "@13")
print(s)
print(s.translate(table))
# string parçalama (string -> list)
liste = "elma-armut-çilek".split('-')
print(liste)
print(liste[0])
print(liste[1])
print(liste[2])
# satırlara göre böl
s = """Turkey
Italy
Spain
France
USA"""
print(s)
liste = s.splitlines()
print(liste)
# önce bir liste tanımlayalım
cities = ["ankara", "bursa", "izmir", "elazığ"]
print(cities)
# liste elemanlarının aralarına = koyarak birleştirik tek bir string yapalım
print("=".join(cities))
# bir string içinde başka bir stringin hangi sırada olduğu:
# 0123456789012
uzun = "I LOVE PYTHON"
print(uzun.index("LOVE")) #2
print(uzun.index("I")) #0
print(uzun.index("PY")) #7
# print(uzun.index("JAVA")) ## HATA FIRLATIR
# bir string içinde başka bir stringin hangi sırada olduğu:
# 0123456789012
uzun = "I LOVE PYTHON"
print(uzun.find("LOVE")) #2
print(uzun.find("I")) #0
print(uzun.find("PY")) #7
print(uzun.find("JAVA")) #-1
# NOT: index ve find farkı: find string'i bulamayınca -1 döndürür, index ise hata fırlatır
# başlık yapma
baslik = "kara ambar kamyoncular derneği"
print(baslik.title()) # Kara Ambar Kamyoncular Derneği
# aramaya sağdan başla
# 01234567890
s = "KOŞ ALİ KOŞ"
print(s.find("KOŞ")) #0
print(s.rfind("KOŞ")) #8
# string içinde başka bir string var mı yok mu
print("ka" in "ankara") #True
print("zz" in "ankara") #False
print("ankara".find("ka") > -1) #True
print("ankara".find("zz") > -1) #False
# hepsi büyük mü
print("Ankara".isupper()) #false
print("ANKARA".isupper()) #true
print("123ANKARA123".isupper()) #true
# büyüğü küçüğe küçüğü büyüğe çevir
s = "KüÇüKlÜ bÜyÜkLü"
print(s.swapcase()) #kÜçÜkLü BüYüKlÜ
# fazlası için:
# https://www.w3schools.com/python/python_strings_methods.asp
| false |
8af2e44e30d2e180e9b16f63c69d2d53d6a1594b | Suman196pokhrel/TkinterPractice | /more_examples/m7e_canvas_and_mouse_events.py | 2,551 | 4.3125 | 4 | """
Example showing for tkinter and ttk how to:
-- Capture mouse clicks, releases and motion.
-- Draw on a Canvas.
Authors: David Mutchler and his colleagues
at Rose-Hulman Institute of Technology.
"""
import tkinter
from tkinter import ttk
class PenData(object):
def __init__(self):
self.color = 'blue'
self.mouse_position_x = None
self.mouse_position_y = None
self.is_dragging = False
def main():
pen_data = PenData()
root = tkinter.Tk()
main_frame = ttk.Frame(root, padding=5)
main_frame.grid()
instructions = 'Click the left mouse button to make circles,\n'
instructions = instructions + 'drag the left mouse button to draw'
label = ttk.Label(main_frame, text=instructions)
label.grid()
# Make a tkinter.Canvas on a Frame.
# Note that Canvas is a tkinter (NOT a ttk) class.
canvas = tkinter.Canvas(main_frame, background='lightgray')
canvas.grid()
# Make callbacks for mouse events.
canvas.bind('<Button-1>', lambda event: left_mouse_click(event))
canvas.bind('<B1-Motion>',
lambda event: left_mouse_drag(event, pen_data))
canvas.bind('<B1-ButtonRelease>',
lambda event: left_mouse_release(pen_data)) # @UnusedVariable
# Make a button to change the color.
button = ttk.Button(main_frame, text='Flip pen color')
button.grid()
button['command'] = lambda: flip_pen_color(pen_data)
root.mainloop()
def left_mouse_click(event):
canvas = event.widget
canvas.create_oval(event.x - 10, event.y - 10,
event.x + 10, event.y + 10,
fill='green', width=3)
def left_mouse_drag(event, data):
# data.mouse_position_x and _y keep track of the PREVIOUS mouse
# position while we are dragging.
canvas = event.widget
if data.is_dragging:
canvas.create_line(data.mouse_position_x, data.mouse_position_y,
event.x, event.y,
fill=data.color, width=5)
else:
data.is_dragging = True # Start dragging
data.mouse_position_x = event.x
data.mouse_position_y = event.y
def left_mouse_release(data):
data.is_dragging = False
def flip_pen_color(data):
if data.color == 'blue':
data.color = 'red'
else:
data.color = 'blue'
# ----------------------------------------------------------------------
# Calls main to start the ball rolling.
# ----------------------------------------------------------------------
main()
| true |
d6577d3cba76440597da1653413a156453e16514 | maainul/Python | /pay_using_try_catch.py | 244 | 4.125 | 4 | try:
Hours=input('Enter Hours:')
Rates=input('Enter Rates:')
if int(Hours)>40:
pay=40*int(Rates)+(int(Hours)-40)*(int(Rates)*1.5)
print(pay)
else:
pay=int(Hours)*int(Rates)
print(pay)
except:
print('Error,Please enter numeric input.')
| true |
dc54502a549f56b66637befa2cbf522f744357c0 | maainul/Python | /Centimeter_to_feet_and_inch.py | 265 | 4.125 | 4 | cm=int(input("Enter the height in centimeters:"))
inches=0.394*cm
feet=0.0328*cm
print("The length in inches",round(inches,2))
print("The length in feet",round(feet,2))
OUTPUT:
Enter the height in centimeters:50
The length in inches 19.7
The length in feet 1.64
| true |
f0efb4420fc64de14a50e2ad08c873ba103fcc11 | kuldeepc08/PythonPrograms | /palindrome.py | 451 | 4.25 | 4 | '''Palindrome number'''
def Reverse(num):
rem=0
while num!=0:
rem=num%10+rem*10
num= int(num//10)
return rem
def main():
num=input("Enter the number")
num1=Reverse(num)
print("Reverse number is %d" %num1)
if (num1==num):
print("Number is palindrome")
else:
print("Number is not palindrome")
if __name__=='__main__':
main()
| false |
4719c9d94b43e37e25802ebdb2f92a8eaeb735a8 | sudheer-sanagala/intro-python-coursera | /WK-03-Loops/while_loops.py | 2,178 | 4.3125 | 4 | # while loops
x = 0
while x < 5:
print("Not there yet, x =" + str(x))
x = x + 1
print("x = "+str(x))
#current = 1
def count_down(start_number):
current = start_number
while (current > 0):
print(current)
current -= 1 #current = current -1
print("Zero!")
count_down(3)
"""
Print prime numbers
A prime factor is a number that is prime and divides another without a remainder.
"""
def print_prime_factors(number):
# Start with two, which is the first prime
factor = 2
# Keep going until the factor is larger than the number
while factor <= number:
# Check if factor is a divisor of number
if number % factor == 0:
# If it is, print it and divide the original number
print(factor)
number = number / factor
else:
# If it's not, increment the factor by one
factor = factor + 1
return "Done"
print_prime_factors(100)
"""
The multiplication_table function prints the results of a number passed to it multiplied
by 1 through 5. An additional requirement is that the result is not to exceed 25,
which is done with the break statement.
"""
def multiplication_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
# What is the additional condition to exit out of the loop?
if result > 25 :
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
multiplication_table(3)
"""
Print multiplication tables
"""
def multiplication_table(number,limit):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= limit:
result = number * multiplier
# What is the additional condition to exit out of the loop?
#if result > 25 :
# break
print(str(number) + " x " + str(multiplier) + " = " + str(result))
# Increment the variable for the loop
multiplier += 1
multiplication_table(3,10)
# break statement
i = 0
while True:
print("Iteration number "+ str(i))
i = i + 1
if i == 10:
break
print("Final value :" +str(i))
| true |
dd0c19ae77a22d440a86212bb03966d240c56b91 | Robbot/ibPython | /src/IbYL/Classes/Polymorphism.py | 1,050 | 4.1875 | 4 | '''
Created on 16 Apr 2018
@author: Robert
'''
class network:
def cable(self): print('I am the cable')
def router(self): print('I am the router')
def switch(self): print('I am the switch')
def wifi(self): print('I am wireless router, cable does not matter')
class tokenRing(network):
def cable(self): print('I am a token ring cable')
def router(self): print('I am a token ring router')
class ethernet(network):
def cable(self): print('I am a ethernet cable')
def router(self): print('I am a ethernet router')
def main():
windows=tokenRing()
mac=ethernet()
#example of polimorphism - this is the same method cable but it takes data from different classes and gives different results
windows.cable()
mac.cable()
# below it is even better implemented
for obj in (windows, mac):
obj.cable()
obj.router()
# obj.wifi is not definied in class windows or mac but it is taken from class network
obj.wifi()
main() | true |
7999ace79084e36c7190d8a1bd42eca5daad30f6 | leon-sleepinglion/daily-interview-pro | /014 Number of Ways to Climb Stairs/main.py | 413 | 4.15625 | 4 | '''
If we look at the solution as a function f(n) where n = number of steps
f(1) = 1
f(2) = 2
f(3) = 3
f(4) = 5
f(5) = 8
f(6) = 13
This is in fact a fibonacci sequence! Hence the solution can be implemented
as a function that calculates the (n+2)th fibonacci number
'''
def staircase(n):
x = [0,1]
for i in range(n):
x.append(x[-1]+x[-2])
return x[-1]
print(staircase(4))
# 5
print(staircase(5))
# 8 | true |
0493b5cd7e50e3b1acd3487d7f0db5c13e9c6e15 | AT1924/Homework | /hw10/functional.py | 1,772 | 4.15625 | 4 | class InvalidInputException(Exception):
def __str__(self):
return "Invalid Input Given."
def apply_all(f_list, n):
"""apply_all: [function], number -> [number]
Purpose: applies each function in a list to a single number
Consumes: a list of functions and a number
Produces: a list of numbers where each number is the result of a function application
Exceptions: InvalidInputException if any of the inputs are None
Example: function_apply([lambda x: x+1, lambda x: x+2, lambda x: x+3], 4) --> [5,6,7]
"""
return map(lambda f: f(n), f_list)
def compose(f_list, n):
"""compose: [function], number -> number
Purpose: composes all of the functions in a list and applies this to a number
Consumes: a list of functions and a number
Produces: a number that is the result of composing all of the functions in the list
and applying this to the number argument
Exceptions: InvalidInputExceiption if any of the inputs are None
Example: compose([lambda x: x+1, lambda x: x+2, lambda x: x+3], 4) --> 10
"""
def comp2(f1, f2):
return lambda x: f1(f2(x))
composed = reduce(comp2, f_list)
composed = reduce(lambda x, y: lambda z: x(y(z)), f_list)
return composed(n)
def list_compose_steps(f_list, n):
"""list_compose_steps: [function], number -> [number]
Purpose: shows all intermediate steps of compose starting with the input number n
Consumes: a list of functions and a number
Produces: a list of numbers that represent the intermediate steps of compose
Exceptions: InvalidInputExceiption if any of the inputs are None
Example: list_compose_steps([lambda x: x+1, lambda x: x+2, lambda x: x+3], 4)
--> [4, 5, 7, 10]
"""
return []
| true |
5463864d5969765af54156c9a19bde20de80b71e | wwyywg/Py3 | /02_python核心编程/01_Python核心编程/ww_07_iterable.py | 628 | 4.125 | 4 | from collections.abc import Iterable, Iterator
if __name__ == '__main__':
# 判断是否可以迭代
# print(isinstance([], Iterable))
# print(isinstance({}, Iterable))
# print(isinstance('abc', Iterable))
# print(isinstance((x for x in range(10)), Iterable))
# print(isinstance(100, Iterable))
# 迭代器
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([], Iterator))
print(isinstance({}, Iterator))
print(isinstance('abc', Iterator))
print(isinstance(100, Iterator))
print(isinstance(iter([]), Iterator))
print(isinstance(iter('abc'), Iterator)) | false |
33655816cfafa233b306d61f4534338cebeced0a | Lord-Gusarov/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 514 | 4.21875 | 4 | #!/usr/bin/python3
"""
Task 1
Write a class Square that defines a square by
>Private instance attribute: size
>Instantiation with size (no type/value verification)
>You are not allowed to import any module
"""
class Square:
"""
A class that defines a Square
"""
def __init__(self, size):
"""Initializes and instance of class Square
takes the size and sets it for the new instance
Args:
size: size for the new instance
"""
self.__size = size
| true |
3f48b004bfa01617330bbcc06c11751187786c86 | Lord-Gusarov/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-write_file.py | 319 | 4.1875 | 4 | #!/usr/bin/python3
"""Task: Write to a file
"""
def write_file(filename="", text=""):
"""writes to a file, overtwiting it if it exist
Args:
filename (str): desire name of the output file
text (str): what is to be written
"""
with open(filename, 'w') as f:
return f.write(text)
| true |
f636dc47edfa679588c09af316acb7a9fc07db5e | Lord-Gusarov/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 960 | 4.46875 | 4 | #!/usr/bin/python3
"""Task2
Write a class Square that defines a square by
Private instance attribute: size
Instantiation with optional size: def __init__(self, size=0):
Size must be an integer, otherwise raise a TypeError exception with the
message size must be an integer
If size is less than 0, raise a ValueError exception with the
message size must be >= 0
"""
class Square:
"""Defines a Square class with an integer size equal or
greater than zero
"""
def __init__(self, size=0):
"""Initializer, validates given size for correct type
and fo correct value. If one of these is not correct,
and exception is raised
Args:
size (int): must be an integer greater or equal to zero
"""
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
self.__size = size
| true |
e38e998dba656061bb5af65d2cd338e0bd30de8b | xinyifuyun/-Python-Programming-Entry-Classic | /chapter_three/02.py | 310 | 4.21875 | 4 | a = ("first", "second", "third")
print("The first element of the tuple is %s" % a[0])
print("The second element of the tuple is %s" % a[1])
print("The third element of the tuple is %s" % a[2])
print("%d" % len(a))
print(a[len(a) - 1])
b = (a, "b's second element")
print(b[1])
print(b[0][0])
print(b[0][2])
| true |
f6568d0cecef38406016d82249b846b7e86efa32 | Ikshitkate/java-html-5-new-project | /python/krishnamurthyNo.py | 778 | 4.15625 | 4 | # Python program to check if a number
# is a krishnamurthy number
# function to calculate the factorial
# of any number
def factorial(n) :
fact = 1
while (n != 0) :
fact = fact * n
n = n - 1
return fact
# function to Check if number is
# krishnamurthy/special
def isKrishnamurthy(n) :
sum = 0
temp = n
while (temp != 0) :
# calculate factorial of last digit
# of temp and add it to sum
rem = temp%10
sum = sum + factorial(rem)
# replace value of temp by temp / 10
temp = temp // 10
# Check if number is krishnamurthy
return (sum == n)
# Driver code
n = int(input())
if (isKrishnamurthy(n)) :
print("YES")
else :
print("NO")
| false |
4226dba34eb2675e4ec98106e3c11eaa0a98f8ce | disha2sinha/Data-Structures-and-Algorithms | /DATA-STRUCTURES/Stack/InfixToPostfixConversion.py | 1,325 | 4.21875 | 4 | def precedence(operator):
if operator == '+' or operator == '-':
return 1
if operator == '*' or operator == '/':
return 2
if operator=='^':
return 3
def postfix(expression):
stack = []
p = ''
stack.append('(')
exp_list.append(')')
for i in range(0, len(exp_list)):
if exp_list[i].isdigit() or exp_list[i].isalpha():
p += exp_list[i]
elif exp_list[i] == "(":
stack.append(exp_list[i])
elif exp_list[i] == '+' or exp_list[i] == '-' or exp_list[i] == '/' or exp_list[i] == '*'or exp_list[i]=='^':
while True:
if stack[len(stack)-1] == '(':
break
if precedence(stack[len(stack)-1]) >= precedence(exp_list[i]):
item = stack.pop()
p += item
else:
break
stack.append(exp_list[i])
elif exp_list[i] == ')':
while True:
if stack[len(stack)-1] == '(':
stack.pop()
break
else:
item = stack.pop()
p += item
return p
expression = input()
exp_list = list(expression)
p = postfix(exp_list)
print(p)
| false |
0a171e7b70560728837047bc976f01c145fcc474 | sartorileonardo/Curso-Intro-Python-Univali | /Aula01/aula01EstruturaRepeticaoWhileFactorial.py | 495 | 4.25 | 4 | print("Teste WHILE")
#O numero factorial é como 5 = 5*4*3*2*1
factorial_number = input("Entre com um número:")
factorial_number = int(factorial_number)
if factorial_number > 0:
step = factorial_number
total = factorial_number
while step > 1:
step -= 1
total *= step
print("O fatorial de %d é %d"%(factorial_number, total))
elif factorial_number == 0:
print("O fatorial de 0 é 1")
else:
print("O fatorial de um número negativo é inválido")
| false |
4d5100673e0f2e9a6647e200d5cbe52f6e17ae42 | NachoBokita/Ejercicios | /EjercicioClase5/ejercicio5.py | 969 | 4.15625 | 4 |
"""
=> Ejercicio 5:
Realizar una función asociar() que reciba como parametro dos listas
de la misma longitud de elementos y devuelva un diccionario de pares
clave-valor asociando cada elemento de ambas listas segun su indice.
Ej:
empleado = ['Juli', 'Carlos', 'Roberto', 'Marta']
categoria = ['Categoria B', 'Categoria C', 'Categoria A', 'Categoria D']
diccionario = asociar(empleado, categoria)
print(diccionario)
>>> {
'Juli': 'Categoria B',
'Carlos': 'Categoria C',
'Roberto': 'Categoria A',
'Marta': 'Categoria D'
}
"""
empleado = ['Juli', 'Carlos', 'Roberto', 'Marta']
categoria = ['Categoria B', 'Categoria C', 'Categoria A', 'Categoria D']
def asociar(lista1, lista2):
return dict(zip(lista1, lista2))
diccionario = asociar(empleado, categoria)
for key, value in diccionario.items():
print(key, ":", value) | false |
b050f7dcbcc0a529ec03ac638af6c04cac4e6026 | Aneeka-A/Basic-Python-Projects | /addition_problems.py | 1,561 | 4.5625 | 5 | """
File: addition_problems.py
-------------------------
This piece of code will create addition problems (with 2 digit numbers).
New problems will continue to be displayed until the user gets 3 correct answes in a row.
"""
import random
# Declaring the minimum and the maximum numbers that can appear in the question.
MIN_NUM = 10
MAX_NUM = 99
# Declaring the number of times one has to give correct answers in a row to master the addition program.
MASTER_ADD = 3
def main():
"""
This program will produce random addition problems
consisting of only two digit numbers that the user
will have to answer.
The program will have to keep producing problems until the
user masters the addition problems, i.e., until the user
answers 3 problems correctly in a row.
"""
correct_in_a_row = 0
while correct_in_a_row < 3:
num_1 = random.randint(MIN_NUM, MAX_NUM)
num_2 = random.randint(MIN_NUM, MAX_NUM)
print("What is " + str(num_1) + " + " + str(num_2) + " ?")
expected_ans = int(num_1) + int(num_2)
expected_ans = int(expected_ans)
inp_ans = input("Your answer: ")
inp_ans = int(inp_ans)
if inp_ans == expected_ans:
correct_in_a_row += 1
print("Correct1 You've gotten {} correct in a row.".format(correct_in_a_row))
else:
correct_in_a_row = 0
print("Incorrect. The expected answer is " + str(expected_ans))
print("Congratulations! You mastered addition.")
if __name__ == '__main__':
main()
| true |
e3d93082e02229e0723365df2f15d2705bc4f625 | RawOnion/AlgorithmLearning | /Algorithm/quickSort.py | 1,007 | 4.28125 | 4 | '''
快速排序
1.选择基准点
2.将列表分成两个子列表:小于基准点元素的列表和大于基准点列表的元素
3.对两个子列表分别进行快速排序
'''
import random
def quick_sort(arr):
if len(arr)<2:
return arr
else:
pivot=random.choice(arr)
pivot_index=arr.index(pivot)
#所有小于基准值的元素组成的子列表
i=0
less=[]
greater=[]
while i<len(arr):
#所有小于基准值的元素组成的列表
if arr[i]<pivot and i!=pivot_index:
less.append(arr[i])
#所有大于基准值的元素组成的列表
if arr[i]>=pivot and i!=pivot_index:
greater.append(arr[i])
i+=1
#python中要list做加法
return quick_sort(less)+[pivot]+quick_sort(greater)
#测试用例
if __name__=="__main__":
print(quick_sort([2,1,5,5,8,9]))
print(quick_sort([293,4,523,456,3,8,3,9]))
print([2]) | false |
2c5b327a4407c39fc58e0fd3183737bb136626b3 | aryoferdyan/Python-Projects-Protek | /Praktikum 08/langkahkerja.py | 1,886 | 4.25 | 4 | print("1.Buatlah list a = [1, 5, 6, 3, 6, 9, 11, 20, 12] dan b = [7, 4, 5, 6, 7, 1, 12, 5, 9")
a = [1,5,6,3,6,9,11,20,12]
b = [7,4,5,6,7,1,12,5,9]
print(a)
print(b)
print('')
print("2.Sisipkan nilai 10 ke dalam indeks ke 3 dari a, dan 15 ke dalam indeks ke 2 dari b")
#insert(indeks ke-9, nilai)
a.insert(3,10)
b.insert(2,15)
print(a)
print(b)
print('')
print("3.Sisipkan nilai 4 ke indeks terakhir dari a, dan 8 ke indeks terakhir dari b")
#insert ke indeks terakhir
a.append(4)
b.append(8,4,2)
print(a)
print(b)
print('')
print("4.Kemudian lakukan sorting secara ascending pada list a dan b")
a.sort()
b.sort()
print(a)
print(b)
print('')
print("5.Buatlah list c yang elemennya merupakan sublist dari a (mulai dari indeks ke 0 s/d 7), dan list d yang elemennya merupakan sublist dari b (mulai indeks ke 2 s/d 9)")
c = a[0:8]
d = b[2:10]
print(c)
print(d)
print('')
print("6.Buatlah serangkaian langkah untuk mendapatkan list e yang elemennya merupakan hasil penjumlahan dari setiap elemen c dan d yang bersesuaian indeksnya.")
e = []
for i in range(len(c)):
n = c[i] + d[i]
e.append(n)
print(e)
print('')
print("7.Ubahlah list e ke dalam tuple")
eTup = tuple(e)
print(eTup)
print('')
print('8.Carilah nilai min, maks, dan jumlahan seluruh elemen dari e')
print('min = ',min(eTup))
print('maks = ',max(eTup))
print('jumlah = ',sum(eTup))
print('')
print('9.Buatlah sebuah string myString = “python adalah bahasa pemrograman yang menyenangkan”')
myString = 'python adalah bahasa pemrograman yang menyenangkan'
print(myString)
print('')
print('10.Dengan menggunakan set() tentukan karakter huruf apa saja yang menyusun string tersebut')
nmyS = set(myString)
print(nmyS)
print('')
print('11.Urutkan secara alfabet himpunan karakter huruf yang diperoleh dari langkah 10, dengan terlebih dahulu mengubahnya ke list. ')
lstm = list(nmyS)
lstm.sort()
print(lstm)
| false |
d001674dd6a054da8536bdfb8565cb423a5e49e2 | Onselius/mixed_projects | /factors.py | 741 | 4.34375 | 4 | #! /usr/bin/python3
# factors.py
# Finding out all the factors for a number.
import sys
def check_args():
if len(sys.argv) != 2:
print("Must enter a number")
sys.exit()
elif not sys.argv[1].isdigit():
print("Must enter a number")
sys.exit()
else:
return True
check_args()
number = int(sys.argv[1])
factors = [str(1), str(number)]
lower = 2
upper = number
while lower < upper:
if number % lower == 0:
upper = int(number / lower)
factors.append(str(lower))
factors.append(str(upper))
lower += 1
factors = list(set(factors))
factors.sort(key=int)
if len(factors) == 2:
print("%s is a prime!" % (number))
factors = ", ".join(factors)
print(factors)
| true |
882145ab3ef396f1cf082b5a6e912dad48597167 | chnandu/practice-problems | /string-problems/unique_chars.py | 644 | 4.25 | 4 | #!/usr/bin/python
# Check if given string has all unique characters or not
def check_uniqueness(str_):
"""Check if given string has all unique characters and return True
:param str_: Given string
:returns: True, if all characters are unique. Else, False.
"""
char_dict = {}
for c in str_:
if char_dict.get(c) is None:
char_dict[c] = 1
else:
print("Duplicate character: %s" % c)
return False
return True
if __name__ == "__main__":
inputs = ["abcdfhefef", "abcdefgh", "1234", "foo"]
for i in inputs:
print("%s --> %s" % (i, check_uniqueness(i)))
| true |
4327f65151e2054c6ece88b694faa02ec3449d09 | Shaaban5/Hard-way-exercises- | /py files/ex9+10.py | 897 | 4.15625 | 4 |
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\tso on" # \n print in new line & \t print tap
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something going on here.
With the three double- quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
print "I am 6'2\" tall." # put \ before double qoute to tel python just print
print 'I am 6\'2" tall.' # put \ before qoute to tel python just print
print "I am 6'2\\ \" tall." # double backslash to tell python print it i need it in my txt
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat | true |
44f95e83ddebe7cf08f73ca9c9e66e4307b1ae58 | Shaaban5/Hard-way-exercises- | /py files/ex27+28.py | 1,613 | 4.1875 | 4 | print True and True # T
print False and True # F
print 1 == 1 and 2 == 1 # F
print "test" == "test" # T
print '\n'
print 1 == 1 or 2 != 1 # T
print True and 1 == 1 # T
print False and 0 != 0 # F
print True or 1 == 1 # T
print '\n'
print "test" == "testing" # F
print 1 != 0 and 2 == 1 # F
print "test" != "testing" # T
print "test" == 1 # F
print '\n'
print not (True and False) # T
print not (1 == 1 and 0 != 1) # F
print not (10 == 1 or 1000 == 1000) # F
print not (1 != 10 or 3 == 4) # F
print '\n'
print not ("testing" == "testing" and "Zed" == "Cool Guy") # T
print 1 == 1 and not ("testing" == 1 or 1 == 0) # T
print "chunky" == "bacon" and not (3 == 4 or 3 == 3) # F
print 3 == 3 and not ("testing" == "testing" or "Python" == "Fun") # F
print '\n'
print 'test' <= "test" # T # QUOTE OR DOUBLE Q DOESNT AFFECT
print 'test' <= 'testI' # T
print 'test' <= 'test-ING' # T # CHECK SAME ORDER AND THEN COMPARE
print 'test' <= 'ING-test' # F # order is important
print '\n'
print True and 'aaaaaaa' # 1st check right side if true check left side then return last one checked
print False and 'aaaaaaa' # 1st check right side found false then return false without checked left side
print 'aaaaaaa' and True ,'\t', 'aaaaaaa' and False # it hase to check the left side
print '\n'
print True or 1 # the oppist in 'or' 1st check right side if rtuen true and doesnt check left side
print False or 1 # 1st check right side if false check left side and return last one checked
print 1 or False,'\t',1 or True # doesnt have to check the left side
print any and True , any and False | true |
9b78e17fab9b4e8c0a71bf89bacb5a2a4caa7b74 | Ruizdev7/pyEjercicios | /listas.py | 1,989 | 4.375 | 4 | miLista=["elem1", 5, 78.35, "elem4"] #estructura de una lista
print(miLista[0])
print(miLista[1])
print(miLista[2])
print(miLista[3])
print(miLista[-1])
print(miLista[-2])
print(miLista[-3])
#Accediendo a porciones de listas
print(miLista[0:3])
print(miLista[:3])
print(miLista[1:2])
print(miLista[2:])
#Funcion append agrega al final de la lista
miLista.append("Joseph")
print(miLista)
#Funcion insert agrega a la lista indicando el indice
miLista.insert(2, "Prueba de Insercion")
print(miLista)
#Funcion extend permite concatenar listas agregando a la original
miLista.extend(["extend1","extend2","extend3" ])
print(miLista)
#Funcion index permite saber cual es el indice de un elemento dentro de la lista
print(miLista.index("Joseph"))
#Funcion in devuelve true o false si el elemento se encuentra en la lista
print("Joseph" in miLista)
#Eliminando elementos
#Funcion remove elimina elemento entre parentesis de la lista
miLista.remove("elem4")
print(miLista[:])
#Funcion pop Elimina el ultimo elemento de la lista
miLista.pop()
print(miLista)
#Operador mas para sumar el contenido de dos listas diferentes
miLista2 = ["Sandra", "Lucia"]
miLista3 = miLista + miLista2
print(miLista3)
#Operador por permite repetir el contenido de la lista por el numero de veces multiplicado
miLista4 = miLista3 * 3
print(miLista4)
'''
upper() convierte el string en mayusculas
lower() convierte el string en minusculas
capitalize() Funcion Nombre propio en excel primera letra en mayuscula como en el ingles
count() contar cuantas veces una cadena
find() representa el indice en el que aparece un dato
isdigit() True or False si el valor es un digito valor numerico o no lo es
isalum() boolean es alfanumerico
isalpha() boolean es alfabetico
split() separa por palabras utilizando espacion
strip() borrar espacios sobrantes al comienzo y al final
replace() reemplaza una letra o palabra por otra
rfind() representa el indice de un caracter
| false |
9fd35de9093f9f05025455b55fb72eb32d2f698d | AsmitaKhaitan/Coding_Challenge_2048 | /2048_game.py | 1,920 | 4.40625 | 4 |
#importing the Algorithm.py file where all the fuctions for the operatins are written
import Algorithm
import numpy as np
#Driver code
if __name__=='__main__':
#calling start() function to initialize the board
board= Algorithm.start()
while(True):
t = input("Enter the number (move) of your choice : ")
#since 3 is for moving UP
if(t=='3'):
#calling the up function to carry out operation
board,c= Algorithm.up(board)
#calling function to get the current status of the game
curr= Algorithm.state(board)
print(curr)
#if game is not over then add a random 2 or 4
if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'):
Algorithm.add_num(board)
else :
break
#the same process like the above if condition is followed for down, left and right
#since "4" is for moving down
elif(t=='4'):
board,c=Algorithm.down(board)
curr= Algorithm.state(board)
print(curr)
if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'):
Algorithm.add_num(board)
else :
break
#since "1" is for moving left
elif(t=='1'):
board,c=Algorithm.left(board)
curr= Algorithm.state(board)
print(curr)
if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'):
Algorithm.add_num(board)
else :
break
#since "2" is for moving right
elif(t=='2'):
board,c=Algorithm.right(board)
curr= Algorithm.state(board)
print(curr)
if(curr == 'CONTINUE PLAYING, THE GAME IS NOT YET OVER!!!'):
Algorithm.add_num(board)
else :
break
else:
print("Invalid choice of move, sorry!")
#print the board after each move
print(np.matrix(board))
| true |
bbab08378125425090805932e229d260c12158d0 | iez1784/learn | /Python/PythonLearnRocket/python_rocket/python_5.py | 1,094 | 4.1875 | 4 | # -*- coding: UTF-8 -*-
__author__ = 'zhangedison'
"""
请写出下面代三运后后的结果,并解释原因
"""
def makeActions(N):
acts = []
for i in range(N):
acts.append(lambda x: i ** x)
return acts
acts = makeActions(5)
print("===makeAction===")
for act in acts:
print(act(2))
print()
"""
第一题当中:
得到结果是:
16,16,16,16,16
makeActions函数中的lambda表达式,表头没有保存参数,函数体只有在调用的时候才会执行,才会去看是否有带参数,所以
acts的值都是[4**x, 4**x, 4**x, 4**x]
最后for act in acts中,act都传了一个x=2的值,所以结果都是4的平方,16
"""
def makeActions2(N):
acts = []
for i in range(N):
acts.append(lambda x, i=i: i ** x)
return acts
acts = makeActions2(5)
print("===makeAction2===")
for act in acts:
print(act(2))
print()
"""
第二题当中,有保存传进参数 i=i,所以acts = [0的x方,1的x方,2的x方,3的x方,4的x方]
最后for act in acts中,传入参数i=2,所以结果是[0,1,4,9,16]
"""
| false |
1978e3ac3665e1c5b096ee01da1da17a967873cd | ckitay/practice | /MissingNumber.py | 998 | 4.3125 | 4 | # All numbers from 1 to n are present except one number x. Find x
# https://www.educative.io/blog/crack-amazon-coding-interview-questions
# n = expected_length
# Test Case 1 , Expect = 6
from typing import List
from unittest import TestCase
class Test(TestCase):
def test1(self):
self.assertEqual(find_missing_number([3, 7, 1, 2, 8, 4, 5], 8), 6)
def test2(self):
self.assertEqual(find_missing_number([3, 1], 3), 2)
def test3(self):
self.assertEqual(find_missing_number([2], 2), 1)
def find_missing_number(nums: List[int], expected_length: int) -> List[int]:
# Find sum of all values in nums
sum_nums = sum(nums)
# Created expectedNums, starting with 1 and ending with expected_length
# expected + 1 because there is exactly 1 number missing
expected_nums = range(1, expected_length + 1)
# Find sum of all expectedNums values
sum_expected = sum(expected_nums)
# Return Missing number
return sum_expected - sum_nums
| true |
d7cfc5ab4e6ee45b677b0b4351d6222e3f96af13 | izukua11might/belajarpython | /for loop.py | 1,072 | 4.125 | 4 | # list sebagai iterable
gorengan = ['bakwan','cireng','tahu isi','tempe goreng','ubi goreng']
for g in gorengan:# g yang di depan for merupakan variable baru
print (g) #yang mengakses data di variable gorengan oleh command for
print(len(g)) #yang di aplikasikan dengan menprint g
#Command len untuk menghitung panjang atau jumlah kata dalam satu kata di dalam data variable
print()
# string sebagai iterable(penerapan looping)
Gorengan = 'bakwan'
for i in Gorengan:
print(i)
print()
# for di dalam for
buah = ['semangka','jeruk','apel','anggur']
sayur = ['kangkung','wortel','tomat','kentang']
Daftar_belanja = [gorengan,buah,sayur]
for subDaftarBelanja in Daftar_belanja:#for pertama menjabarkan list Dalam variaabel Dafta_belanja
print(subDaftarBelanja)
for komponen in subDaftarBelanja:#for kedua menguraikan list per komponen kata
print(komponen)
for lagi in komponen:#for ketiga lebih membedah data dan lebih menguraikan nya satu persatu dari list nya
print(lagi)
| false |
452b696d838bfd7d77b0c02ea9129f168d6b1786 | SuproCodes/DSA_PYTHON_COURSE | /OOP.py | 1,994 | 4.125 | 4 | class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # John
#----------------------------
# Dog class
class Dog:
# Method of the class
def bark(self):
print("Ham-Ham")
# Create a new instance
charlie = Dog()
# Call the method
charlie.bark()
# This will output "Ham-Ham"
#-----------------------------
class Car:
"This is an empty class"
pass
# Class Instantiation
ferrari = Car()
#-----------------------------
class my_class:
class_variable = "I am a Class Variable!"
x = my_class()
y = my_class()
print(x.class_variable) #I am a Class Variable!
print(y.class_variable) #I am a Class Variable!
#-----------------------------
class Animal:
def __init__(self, voice):
self.voice = voice
# When a class instance is created, the instance variable
# 'voice' is created and set to the input value.
cat = Animal('Meow')
print(cat.voice) # Output: Meow
dog = Animal('Woof')
print(dog.voice) # Output: Woof
#-------------------------------
a = 1
print(type(a)) # <class 'int'>
a = 1.1
print(type(a)) # <class 'float'>
a = 'b'
print(type(a)) # <class 'str'>
a = None
print(type(a)) # <class 'NoneType'>
#-------------------------------
# Defining a class
class Animal:
def __init__(self, name, number_of_legs):
self.name = name
self.number_of_legs = number_of_legs
#-----------------------------
class Employee:
def __init__(self, name):
self.name = name
def print_name(self):
print("Hi, I'm " + self.name)
print(dir())
# ['Employee', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'new_employee']
print(dir(Employee))
# ['__doc__', '__init__', '__module__', 'print_name']
#---------------------------
#<class '__main__.CoolClass'>
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| true |
f6e13f9d47f8524f63c175d086f49de917c678d4 | vipin-s0106/DataStructureAndAlgorithm | /Linkedlist/reverse_linked_list.py | 1,465 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def add(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
temp = self.head
while (temp.next != None):
temp = temp.next
temp.next = new_node
def print_list(self):
temp = self.head
while (temp != None):
print(temp.data, end=" ")
temp = temp.next
print("")
def linkedlist_length(self):
count = 0
temp = self.head
while temp is not None:
count += 1
temp = temp.next
return count
def reverse_linked_list(self):
prev = None
current = None
fast = self.head
while fast != None:
current = fast
fast = fast.next
current.next = prev
prev = current
self.head = current
def reverseLinkedList_recursion(self,prev,cur):
if cur == None:
return
self.reverseLinkedList_recursion(cur,cur.next)
if cur.next == None:
self.head = cur
cur.next = prev
l = Linkedlist()
l.add(1)
l.add(2)
l.add(3)
l.add(4)
l.add(6)
l.print_list()
l.reverse_linked_list()
l.print_list()
l.reverseLinkedList_recursion(None,l.head)
l.print_list()
| true |
fd879e688bc00a100698b5f53fcf5731c22ebcd4 | AlanAloha/Learning_MCB185 | /Programs/completed/at_seq_done.py | 694 | 4.1875 | 4 | #!/usr/bin/env python3
import random
#random.seed(1) # comment-out this line to change sequence each time
# Write a program that stores random DNA sequence in a string
# The sequence should be 30 nt long
# On average, the sequence should be 60% AT
# Calculate the actual AT fraction while generating the sequence
# Report the length, AT fraction, and sequence
seq = ''
at_count = 0
for i in range(30):
n = random.randint(1,10);
print(n,end=' ')
if 1<=n<=3:
seq+='A'
at_count+=1
elif 4<=n<=6:
seq+='T'
at_count+=1
elif 7<=n<=8: seq+='G'
else: seq+='C'
print('\n',len(seq), at_count/len(seq), seq)
"""
python3 at_seq.py
30 0.6666666666666666 ATTACCGTAATCTACTATTAAGTCACAACC
"""
| true |
8241b6ba8e8ddb44e4cef872bab429c057b54c02 | lalusafuan/DPL5211Tri2110 | /Lab 2.6.py | 308 | 4.125 | 4 | # Student ID: 1201201699
# Student Name : Lalu Muhammad Safuan Bin Maazar
import math
radius = float(input("Enter radius :"))
volume = (4/3)*math.pi * radius**3
surface = 4 * math.pi * radius **2
print("The volume of the sphrere is : {}".format(volume))
print("The surface area of the sphrere is : {}".format(surface)) | false |
01d632d6197fb44a76eadc59fba2ea73f48d3c70 | jptheepic/Sudoku_Solver | /main.py | 2,359 | 4.21875 | 4 |
#The goal of this project is to create a working sudoku solver
#This solution will implement recustion to solve the board
#This function takes in a 2D array and will print is as a sudoku board
def print_board(board):
for row in range(0,len(board)):
for col in range(0,len(board)):
#prints the boarder for the right side of the board
if col ==0:
print("|",end=' ')
#Prints the boarder for the right side of the board
if col ==8:
endline = ' |\n'
elif (col+1)%3 == 0:
endline = "|"
elif (row+1)%3 == 0:
endline = "_"
else:
endline = " "
if board[row][col] ==0:
print(" ", end=endline)
else:
print(board[row][col], end=endline)
#This function takes in a postion and a number and returns weather the placement is valid
def valid(board, row, col,number):
#Checks to see if that number shares a row
for i in range(0,len(board)):
if (board[row][i] == number and col != i):
return False
#checks to see if that number shars a col
for j in range(0,len(board)) :
if (board[j][col] == number and row != j):
return False
#This is the logic used to check if the nuber shares a box
x = (col//3)*3
y = (row//3)*3
for i in range(y, y + 3):
for j in range(x , x + 3):
if (board[i][j] == number ):
return False
return True
def find_empty(board):
for row in range(len(board)):
for col in range(len(board)):
if board[row][col] == 0:
return (row,col)
return None
def solve(board):
empty_position = find_empty(board)
#If no more empty positions return true
if not empty_position:
return True
else:
row, col = empty_position
for num in range(1,10):
if valid(board,row,col,num):
board[row][col] = num
if solve(board):
return True
board[row][col] = 0
return False
if __name__ == '__main__':
board =[
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]]
print('#'*8 + " Original Board " +'#'*8)
print_board(board)
print('#'*8 + " Sovled Board " +'#'*8)
solve(board)
print_board(board) | true |
959f6649dcedb7c3521a54fcf325126b3a5cc4b9 | Lamchungkei/Unit6-02 | /yesterdays.py | 830 | 4.3125 | 4 | # Created by: Kay Lin
# Created on: 28th-Nov-2017
# Created for: ICS3U
# This program displays entering the day of the week then showing the order
from enum import Enum
# an enumerated type of the days of the week
week = Enum('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
# input
print('Sunday(1), Monday(2), Tuesday(3), Wednesday(4), Thursday(5), Friday(6), Saturday(7)')
input_day = raw_input('Enter your favorite day of the week: ')
# process
input_day = input_day.title()
if input_day in week:
counter = 1
for a_day in week:
if input_day == str(a_day):
print (str(counter) + ' is the number that corresponds to your favourite day of the week')
else:
counter = counter + 1
else:
print('Please input valid day')
print('\n')
| true |
6345ba09eeaf5446e3202fef5c2a8faa43591d9d | ArildH/Python-exercises | /if-loop-test.py | 476 | 4.15625 | 4 | #test of for loops
students = {}
students[001] = "Arild Heyyland";
students[002] = "Turid Hoeyland";
students[003] = "Oddrun H. Heyyland";
students[004] = "Harald Heyyland";
students[005] = "Signe Heyyland";
students[006] = "Arne Heyyland";
students[007] = "Ivar Heyyland";
def search_students(student_no):
for key in students:
if key == student_no:
return students[key]
return "No student with that number found"
def find_student(student_no):
print search_students(student_no)
find_student(0037)
| false |
afd1a5dc6d85d64c9a6300a420a8253fb9d8d6e9 | yiboliu26/yibopython | /practice83.py | 1,630 | 4.15625 | 4 | def city_country(city_name, country_name):
"""show_city_info"""
city = city_name + ', ' + country_name
return city.title()
place = city_country('santiago', 'chile')
print(place + "!")
place = city_country('tokyo', 'japan')
print(place + "!")
place = city_country('beijing', 'china')
print(place + "!")
place = city_country('dallas', 'usa')
print(place + "!")
def make_album(singer_name, album_name):
"""singer_and_album_info"""
person = {'singer': singer_name, 'album': album_name}
return person
musician = make_album('taylor', '1989')
print(musician)
musician = make_album('drake', 'hotline')
print(musician)
musician = make_album('bieber', 'despacito')
print(musician)
def make_album(singer_name, album_name, number=''):
"""singer_and_album_info"""
person = {'singer': singer_name, 'album': album_name}
if number:
person['number'] = number
return person
musician = make_album('taylor', '1989', number = 20)
print(musician)
musician = make_album('drake', 'hotline', number = 21)
print(musician)
musician = make_album('bieber', 'despacito', number = 10)
print(musician)
def make_album(singer_name, album_name):
"""album_info"""
album = singer_name + ' ' + album_name
return album.title()
while True:
print("\nnPlease tell me your favorite singer name:")
print("(Enter 'q' at any time to quit)")
s_name = input("Singer name: ")
if s_name == 'q':
break
a_name = input("Album name: ")
if a_name == 'q':
break
favorite_album = make_album(s_name, a_name)
print("\nMy favorite album is " + favorite_album.title() + "!")
| false |
854300cb49d11a58f9b72f1f3a59d4a12012cd9c | jb3/aoc-2019 | /day-3/python/wire.py | 1,486 | 4.15625 | 4 | """Structures relating to the wire and points on it."""
import typing
from dataclasses import dataclass
@dataclass
class Point:
"""Class representing a point in 2D space."""
x: int
y: int
def right(self: "Point") -> "Point":
"""Return a new point 1 unit right of the point."""
return Point(self.x + 1, self.y)
def left(self: "Point") -> "Point":
"""Return a new point 1 unit left of the point."""
return Point(self.x - 1, self.y)
def up(self: "Point") -> "Point":
"""Return a new point 1 unit up from the point."""
return Point(self.x, self.y + 1)
def down(self: "Point") -> "Point":
"""Return a new point 1 unit down from the point."""
return Point(self.x, self.y - 1)
def __hash__(self: "Point") -> int:
"""Convert the Point to a form which Python can hash."""
return hash((self.x, self.y))
def manhattan_distance(self: "Point", other: "Point") -> int:
"""Calculate the manhattan distance between two points."""
return abs(self.x - other.x) + abs(self.y - other.y)
class Wire:
"""Class reprensenting an electrical wire."""
def __init__(self: "Wire", points: typing.List[Point]) -> None:
"""Instantiate a new wire given a list of points."""
self.points = points
def dist_to(self: "Wire", point: Point) -> int:
"""Calculate how far along the wire this point is."""
return self.points.index(point)
| true |
647d1d36759511e86ef6434c8a59daf7b345e888 | AnushSomasundaram/Anush_Python_projects | /Anush_assignments/1st_sem/python/first assignment/area_of_triangle.py | 221 | 4.15625 | 4 | #Write a program to find the area of triangle given
# base and height.
def area_of_triangle(height,base):
area = 0.5*height*base
print("The area of the given trianle is ",area,"units.")
area_of_triangle(1,6)
| true |
1c527311d782ceeec6e04e27d6f4b70e0532f9e4 | AnushSomasundaram/Anush_Python_projects | /chap4_fuctions/lambda.py | 458 | 4.25 | 4 | #lambda functions are just inline functions but specified with the keyword lambda
def function_1(x):return x**2
def function_2(x):return x**3
def function_3(x):return x**4
callbacks=[function_1,function_2,function_3]
print("\n Named Functions")
for function in callbacks:
print("Result:",function(3))
callbacks=\
[lambda x:x**2,lambda x:x**3,lambda x:x**4]
print("Anonymous Functions:")
for function in callbacks:
print("Result",function(3))
| true |
3b9a3df013329cc99b8ac392ca6d1f2c1bbcbcde | AnushSomasundaram/Anush_Python_projects | /compsci_with_python/chap2/largestword.py | 310 | 4.125 | 4 | length= int(input("Enter the number of elements in the list"))
words=[]
for i in range (0,length):
print("Word no.",i,":-")
words.append(str(input()))
longest=0
for i in range (1,length):
if len(words[i])>len(words[longest]):
longest=i
print("longest word is :-",words[longest])
| true |
cb7875e93bb7619218691f2beba46a87f691d96c | AnushSomasundaram/Anush_Python_projects | /Anush_assignments/1st_sem/python/first assignment/operations.py | 598 | 4.125 | 4 | """Write a Python program that allows the user to enter two integer values,
and displays the results when each of the following arithmetic operators are applied. For example,
if the user enters the values 7 and 5, the output would be,
7+5=12
7-5=2 and so on."""
number1=int(input("Please enter the first integer:-"))
number2=int(input("\nPlease enter the second integer:-"))
sum=number1+number2
difference=number1-number2
print("\The sum of the two integers is",number1,"+",number2,"=",sum," .")
print("\nThe difference between the two integers is",number1,"-",number2,"=",difference," .")
| true |
76d43d9bc8db00125fde1eb88ffb25d7546b43c8 | MithilRocks/python-homeworks | /bitwise_homework/divisible_by_number.py | 399 | 4.3125 | 4 | # hw: wtp to check if a number is multiple of 64
def divisible_by_number(num):
if num & 63 == 0:
return True
else:
return False
def main():
number = 128
if divisible_by_number(number):
print("The number {} is divisble by 64".format(number))
else:
print("The number {} is not divisble by 64".format(number))
if __name__ == "__main__":
main()
| true |
0880f00fcc0cda49c2cbd4de54e5ed0969156f3b | MYadnyesh/Aatmanirbhar_program | /Week 1/add.py | 512 | 4.15625 | 4 | #Program 1:- Addition of 2 numbers
def add(x,y):
print("The addition is : ")
return x+y
while True:
print(add(int(input("Enter 1st number: ")),int(input("Enter 2nd number: "))))
a=input("Do you want to continue (Press Y to continue)")
if(a=='y' or a=='Y') is True:
continue
else:
break
#***********Output**********
# Enter 1st number: 45
# Enter 2nd number: 55
# The addition is :
# 100
# Do you want to continue (Press Y to continue)y
# Enter 1st number:
| true |
b45735562a84f066be681ba592a610118e6da06c | MYadnyesh/Aatmanirbhar_program | /Week 1/primeIntr.py | 633 | 4.1875 | 4 | #Program 2 :- To print all the Prime numbers in an given interval
lower = int(input("Enter a starting number"))
upper = int(input("Enter a ending number "))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
# ******OUTPUT******
# Enter a starting number100
# Enter a ending number 200
# Prime numbers between 100 and 200 are:
# 101
# 103
# 107
# 109
# 113
# 127
# 131
# 137
# 139
# 149
# 151
# 157
# 163
# 167
# 173
# 179
# 181
# 191
# 193
# 197
# 199 | true |
a177115cde3a19cf9e2397aa844610b5a62ffb0c | CIS123Sp2020A/extendedpopupproceed-tricheli | /main.py | 614 | 4.21875 | 4 | #Tenisce Richelieu
from tkinter import
import tkinter.messagebox as box
#The first step after imports is crate a window
window = Tk()
#This shows up at the top of the frame
window.title('Message Box Example')
#create the dialog for the window
def dialog():
var = box. askyesno('Message Box', 'Proceed?')
if var == 1:
box.showinfo('Yes Box', 'Proceeding...')
else:
box.showwarning('No Box', 'Cancelling...')
#creating a button
btn = Button(window, text='Click', command= dialog)
#have to pack the button
btn.pack(padx = 150, pady = 50)
#start the action and keep it going
window.mainloop()
| true |
d625e1281292b5111a2387c83179662dcee3690a | Rishabh450/PythonConcepts | /mutability.py | 807 | 4.125 | 4 | friends_last_seen ={
'name': 'Rishabh',
'id': 15
}
print(id(friends_last_seen))
friends_last_seen ={
'name': 'Rishabh',
'id': 15
}
print(id(friends_last_seen))
# mutable object, when dictionary is passed in argument the change occus
# in same memory location same object, be careful this can be dangerous
friends_last_seen['name'] = 'Sajal'
print(id(friends_last_seen))
# non mutable object
my_int = 5
print(id(my_int))
# my_int = my_int+1 # my_int.__add__() invoked
my_int += +1
print(id(my_int))
# mutable when += used
primes = [2, 3, 5]
print(id(primes))
primes += [7, 11]
print(id(primes))
# non mutable when + or - used
primes = [2, 3, 5]
print(id(primes))
primes +=[7, 11]
print(id(primes))
primes = [2, 3, 5]
print(id(primes))
prime = [7,11]
primes.append([7, 11])
print(id(primes))
| false |
99dbdf5273d32350e7a7186cfeb2dca59819bbae | surajnikam21/simplePatterns.py | /basic/3conditions.py | 618 | 4.25 | 4 | #if else
num1 = 2
num2 = 3
if (num1 == num2):
print('Equals')
else:
print('Not Equals')
# multi if elif els
if(num1 != num2):
print('Not Equal')
elif(num1 == num2):
print("Equals")
elif(num1 > num2 ):
print("num1 > num2")
else:
print("some data")
str1 = 'Suraj'
str2 = 'suraj'
if(str1== str2):
print("String equals")
else:
print('String not equals')
if(str1.lower() == str2.lower()):
print("String equals")
else:
print('String not equals')
str3='birender'
if(str1.lower() == str2.lower() == str3.lower()):
print("String equals")
else:
print('String not equals') | false |
d251c01650c960e33c1414cbba09e7ec68b12d39 | KenOtis/Rock-Paper-Scissors-Game | /RockPaperScissors.py | 1,343 | 4.15625 | 4 | import random
import time
def main():
a=["rock","paper","scissors"]
go="yes"
print("\nLets play Rock, Paper, Scissors! \nBest of 3 wins.")
computer=0
user=0
while (computer<2 or user<2 ):
b=(random.choice(a))
choice=input("Your choice: ")
time.sleep(2)
print ("Computer choice: ",b,"\n")
if choice == "rock":
if b== "scissors":
user+=1
print ("You win!\n")
if b== "paper":
computer+=1
print ("Computer wins!\n")
if choice == "scissors":
if b== "paper":
computer+=1
print ("Computer Wins!\n")
if b== "rock":
user+=1
print ("You wins!\n")
if choice == "paper":
if b== "scissors":
user+=1
print ("You win!\n")
if b== "rock":
computer+=1
print ("Computer wins!\n")
if choice == b:
print ("Tie! no one gets a point.\n")
if computer>2:
print ("Computer Won!\nThanks for playing!")
break
if user>2:
print("You win!\nThanks for playing!")
break
main() | false |
7ec6c5f2363d20cdd567aff4f9cc48718e77f895 | silastsui/pyjunior | /strloops/backwards.py | 551 | 4.15625 | 4 | #!/usr/bin/python
#backwards
text = str(raw_input("Enter a phrase: "))
#solution1 (wat)
print text[::-1]
#solution2 (for x in range)
reverse = ""
a = len(text)
for x in range(len(text)-1, -1,-1):
reverse += text[x]
print reverse
#solution3 (for let in text)
backwards = ""
for let in text:
backwards = let + backwards
print backwards
#solution4 (reverse)
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print reverse(text)
#solution5
reverse = ""
for x in reversed(text):
reverse += x
print reverse
| true |
41b6e2352903bb2459a65f981655f9c7ed7ce60b | silastsui/pyjunior | /intloops/bin2dec.py | 245 | 4.125 | 4 | #!/usr/bin/python
#bin2dec converter
def bin2dec(num):
power = len(num)-1
dec = 0
for x in num:
dec = dec + int(x)*(2**power)
power -= 1
return dec
num = raw_input("Enter a binary number: ")
print bin2dec(num)
| false |
1802b34d83cbfb6b9026a99c6e30da00d950fa5c | strikingraghu/Python_Exercises | /Ex - 04 - Loops.py | 2,676 | 4.125 | 4 | """
In general, statements are executed sequentially.
The first statement in a function is executed first, followed by the second, and so on.
There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
Loop Type & Description
WHILE LOOP
Repeats a statement or group of statements while a given condition is TRUE.
It tests the condition before executing the loop body.
FOR LOOP
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
NESTED LOOP
You can use one or more loop inside any another while loop, for loop or do..while loop.
"""
# While Loop
simple_count = 0
while simple_count < 10:
simple_count += 1
print("Loop Executed =", simple_count)
print("Good Bye!")
print("--------------------------")
another_count = 0
while another_count < 5:
another_count += 1
print(another_count, "is the while loop's value")
else:
if another_count == 5:
print("Ending while loop execution!")
print("--------------------------")
# Takes user's input
user_input = int(input("Enter an integer value :"))
total_value = 0
iterable_value = 1
while iterable_value <= user_input:
total_value = total_value + iterable_value
iterable_value += 1
print("Sum Value =", total_value)
print("End of the execution")
print("--------------------------")
# For Loop
sample_string = 'Bangalore'
for each_letter in sample_string:
print(each_letter)
print("Printed every letter of the word :", sample_string)
print("--------------------------")
# For Loop (Includes Indexing)
fruits = ['Mango', 'Apple', 'Pine', 'Orange', 'Papaya']
for each_fruit in fruits:
print("Fruit Name =", each_fruit, "& it's Index value =", fruits.index(each_fruit))
print("Good Bye!")
print("--------------------------")
# For Loop (Is this a Prime number?)
for num in range(10, 20):
for i in range(2, num):
if num % i == 0:
j = num / i
print('%d equals %d * %d' % (num, i, j))
break
else:
print(num, 'is a prime number')
print("Good Bye!")
print("--------------------------")
# Nested Loop
x = 2
while x <= 100:
y = 2
while y <= x / y:
if not x % y:
break
y += 1
if y > x / y:
print(x, " is a prime number")
x += 1
print("Done")
print("--------------------------")
| true |
d5d43273000fb4a88b57e33c5fa7377264f2a707 | strikingraghu/Python_Exercises | /Ex - 14 - File Handling.py | 1,925 | 4.53125 | 5 | """
In this article, you'll learn about Python file operations.
More specifically, opening a file, reading from it, writing into it, closing it and various file methods.
"""
import os
# Opening File
file_open = open("c:/python_file.txt")
print(file_open) # We can see the path of file, mode of operation and additional details!
print("Class =", type(file_open))
# Reading Contents
print("--------------------------")
print(file_open.read())
print("--------------------------")
# Write Operations
print("--------------------------")
write_some_data = open("c:/python_write_operation.txt", 'w') # New File
write_some_data.write("Contents available in this file is been pushed via Python script!\n"
"However, you can read contents without any fees\n"
"By the way, are you from Bangalore city?")
write_some_data.close()
write_some_data = open("c:/python_write_operation.txt", 'r')
print(write_some_data.read())
write_some_data.close()
print("--------------------------")
# Reading Specific Lines
write_some_data = open("c:/python_write_operation.txt", 'r')
print(write_some_data.read(65)) # Specifically displaying few characters
write_some_data.close()
# File Object Attributes
print("Is file closed? =", write_some_data.closed) # Returns TRUE / FALSE
print("What is the file name? =", write_some_data.name) # Returns Name
print("Can we see the file buffer information? =", write_some_data.buffer) # Returns Buffer!
print("What is the file encoding results? =", write_some_data.encoding) # Returns File Encoding Relevant Info
print("--------------------------")
# Python Files & Directory Management
# Import OS Module (@Start of this script)
print("Current Working Directory =", os.getcwd())
os.chdir("C:\\Users\\")
print("Changing Directory Path = Done")
print("After Changing Directory Path =", os.getcwd())
| true |
5fa07f44836ffb22fcd8a237bc1cf8e572c154ac | strikingraghu/Python_Exercises | /Ex - 08 - Tuples.py | 2,146 | 4.28125 | 4 | """
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
Differences between tuples and lists are, the tuples cannot be changed unlike lists!
Also, tuples use parentheses, whereas lists use square brackets.
"""
sample_tuple_01 = ('Ram', 3492, 'Suresh')
sample_tuple_02 = (28839.23, 'Hemanth', 684.J, 'Bangalore')
print()
print(sample_tuple_01)
print(sample_tuple_02)
# Displaying ID
print("sample_tuple_01 - ID =", id(sample_tuple_01))
print("sample_tuple_02 - ID =", id(sample_tuple_02))
# Equality Test
tuple_001 = ('Ram', 3492, 'Suresh')
print()
print("ID - tuple_001 =", id(tuple_001))
tuple_002 = tuple_001
print("ID - tuple_002 =", id(tuple_001))
print("Both tuples are having same ID's, where assignment attaches name to an object!")
print("Assigning from one reference to another, puts two name tags to an object.")
print(tuple_001)
print(tuple_002)
print("--------------------------")
# Generic Tuple Operations
tuple_007 = ('Yogesh', 'Bangalore', 'Idly', 329091, 293.3772, 'Delhi', 291, 952, 'KKR', 'RCB', 'Virat')
tuple_008 = (3881, 9486142938.4992, 37, 887452.27610020991, 3889, 583, 8331)
print("Length =", len(tuple_007))
print("Get Index Value =", tuple_007.index('Bangalore'))
print("Tuple's Size =", tuple_007.__sizeof__())
print("Tuple's Class Info =", tuple_007.__class__)
print("Value (Virat) Contains Test =", tuple_007.__contains__('Virat'))
print("Value (Dhoni) Contains Test =", tuple_007.__contains__('Dhoni'))
print("Object's Attributes List =", tuple_007.__dir__())
print("--------------------------")
# Few Tuple Operations
print("Get Value (Index Value 10) =", tuple_007.__getitem__(10))
print("Another Way - Tuple's Length (__len__) =", tuple_007.__len__())
tiny_tuple = ('Chennai', 'Modi')
print("After Adding 2 Elements - ID Changed =", id(tuple_007.__add__(tiny_tuple)))
print("However, 'tuple_007' ID =", id(tuple_007))
print("Max Element =", max(tuple_008))
print("Min Element =", min(tuple_008))
print("All Elements Iterable? all() =", all(tuple_008))
print("--------------------------")
| true |
041fa7d58b4c8916abf660eb1bfa82ff8f1b0b6f | SaketSrivastav/epi-py | /trees/check_bst.py | 1,156 | 4.1875 | 4 | #! /usr/bin/python
class Check_Bst():
def check_balanced(self, node):
"""
Input: A tree node
Output: (+)ve number if BST is balanced, otherwise -1
Description: Start with root node and calculate the height of the left
subtree and right subtree. If an absolute difference of heght of left and
right subtree is 0 or 1 then we say the tree node at N is balanced
otherwise its unbalanced.
"""
#Base Case
if not node:
return 0
# Check if left subtree is balanced
left_height = self.check_balanced(node.left)
if left_height == -1:
return -1
# Check if right subtree is balanced
right_height = self.check_balanced(node.right)
if right_height == -1:
return -1
# If both subtree are balanced
if abs(left_height - right_height) > 1:
return -1
# Return the height of node n
return (1 + max(left_height, right_height))
def check_bst(self, my_bst):
is_balanced = self, self.check_balanced(my_bst.get_root())
return is_balanced
| true |
454081e675b5dfb9a82293d3a79fa2ff90be90fc | rakibkuddus1109/pythonClass | /polymorphism.py | 763 | 4.375 | 4 | # polymorphism : Many ways to define the method
# Method overloading
# Method overriding
# Method overloading: Considering relevant methods based upon no. of arguments that method has
# even though the method names are same
# Python doesn't support method overloading
# class Operation:
# def mul(self,a,b,c):
# return (a+b)*(a-c)
# def mul(self,a,b):
# return a*b
# # def mul(self,a,b,c):
# # return (a+b)*(a-c)
# obj = Operation()
# print(obj.mul(4,5))
# Method overriding: Considering the child class method even though parent class method is present
class First:
def add(self,a,b):
return a+b
class Second(First):
def add(self,a,b):
return a*b
obj = Second()
print(obj.add(5,6)) | true |
99355f7b9957a8dcd2c176e4436969861e571a2b | rakibkuddus1109/pythonClass | /exception_handling.py | 1,837 | 4.34375 | 4 | # Exception Handling: Handling the exception or error
# In-built exception : comes with programming language itself
# User-defined exception : setting up our own defined exception
# In-built exception:
# a = [6,5.6,'Python',0,67]
# for j in a:
# print(1/j) # this would give in-built exception when 'Python' would come for division
"""
try:
<statement>
except:
<statement>
"""
# try : those lines which may give an error, has to be written inside 'try' block
# except : statements which should be executed after error occurance, comes under 'except' block
# 'try' block should have minimum one 'except' block
# import sys # importing to know the type of error
# a = [6,5.6,'Python',0,67]
# a = [6,5.6,'Python',0,67,(12,23)]
# for j in a:
# try:
# print(1/j)
# # except:
# # print("Error has occured for",j,sys.exc_info()[0])
# except TypeError:
# print("You have tried to divide with different type of data")
# except ZeroDivisionError:
# print("You are trying to divide by 0")
# except:
# print("Undefined error has occured!")
# print("Execution is over.")
# User-defined exception:
class ValueSmallError(Exception): # Inherit "Exception" class to make it as an exception class
pass
class ValueLargeError(Exception):
pass
num1 = int(input("Enter num1 value:"))
while True:
try:
num2 = int(input("Enter num2 value:"))
if num2 < num1:
raise ValueSmallError # to call exception class use "raise"
elif num2 > num1:
raise ValueLargeError
else:
print("Number guessed correctly!")
break
except ValueSmallError:
print("Value entered is smaller, try again!")
except ValueLargeError:
print("Value entered is larger, try again!") | true |
01d9fb6b2beaaf0ec20b04968465667abf6e7a42 | ivan-yosifov88/python_basics | /Nested Conditional Statements/03. Flowers.py | 954 | 4.125 | 4 | numbers_of_chrysanthemums = int(input())
number_of_roses = int(input())
number_of_tulips = int(input())
season = input()
is_day_is_holiday = input()
chrysanthemums_price = 0
roses_price = 0
tulips_price = 0
bouquet_price = 0
if season == "Spring" or season == "Summer":
chrysanthemums_price = 2
roses_price = 4.1
tulips_price = 2.5
elif season == "Autumn" or season == "Winter":
chrysanthemums_price = 3.75
roses_price = 4.5
tulips_price = 4.15
bouquet_price = numbers_of_chrysanthemums * chrysanthemums_price + number_of_roses * roses_price + number_of_tulips * tulips_price
if is_day_is_holiday == "Y":
bouquet_price *= 1.15
if number_of_tulips > 7 and season == "Spring":
bouquet_price *= 0.95
if number_of_roses >= 10 and season == "Winter":
bouquet_price *= 0.9
if (number_of_roses + number_of_tulips + numbers_of_chrysanthemums) > 20:
bouquet_price *= 0.8
bouquet_price += 2
print(f"{bouquet_price:.2f}")
| true |
bc1e774ca217588ba4a73263971168008f430fe0 | ivan-yosifov88/python_basics | /Exams -Training/05. Movie Ratings.py | 706 | 4.15625 | 4 | import sys
number_of_films = int(input())
max_rating = 0
movie_with_max_rating = ""
min_rating = sys.maxsize
movie_with_min_rating = ""
total_sum = 0
for films in range(number_of_films):
movie_title = input()
rating = float(input())
total_sum += rating
if rating > max_rating:
max_rating = rating
movie_with_max_rating = movie_title
if rating < min_rating:
min_rating = rating
movie_with_min_rating = movie_title
average_rating = total_sum / number_of_films
print(f"{movie_with_max_rating} is with highest rating: {max_rating:.1f}")
print(f"{movie_with_min_rating} is with lowest rating: {min_rating:.1f}")
print(f"Average rating: {average_rating:.1f}")
| true |
6b71ca64eda2419f32feae09a63cb0967b0d1da9 | ivan-yosifov88/python_basics | /Conditional Statements- Exercise/18. Weather Forecast - Part 2.py | 299 | 4.125 | 4 | temperature = float(input())
if 26 <= temperature <= 35:
print("Hot")
elif 20.1 <= temperature <= 25.9:
print("Warm")
elif 15 <= temperature <= 20:
print("Mild")
elif 12 <= temperature <= 14.9:
print("Cool")
elif 5 <= temperature <= 11.9:
print("Cold")
else:
print("unknown") | false |
c61bb81014dba0334bb13516bd8044cc520bde54 | Williano/Solved-Practice-Questions | /MaleFemalePercentage.py | 1,308 | 4.1875 | 4 | # Script: MaleFemalePercentage.py
# Description: This program ask the user for the number of males and females
# registered in a class. The program displays the percentage of
# males and females in the class.
# Programmer: William Kpabitey Kwabla
# Date: 11.03.17
# Declaring the percentage variable for the percentage of the students.
PERCENTAGE = 100
# Defining the main function
def main():
# Asking the user for the number of males in the class.
males = int(input("Please enter the number of males in the class: "))
# Asking the user for the number of females in the class.
females = int(input("Please enter the number of females in the class: "))
# Calculating the total of the number of males and females.
total_students = males + females
# Finding the percentage of males.
percentage_of_males = (males / total_students) * PERCENTAGE
# Finding the percentage of females.
percentage_of_females = (females / total_students) * PERCENTAGE
# Displaying the total percentage to the user.
print("The percentage of males in the class is: ", format(percentage_of_males, ".0f"))
print("The percentage of females in the class is: ", format(percentage_of_females, ".0f"))
# Calling the main function to start execution of the program.
main()
| true |
2582a618219a2e0d3d43d30273d576a824303311 | Williano/Solved-Practice-Questions | /mass_and_weight.py | 1,791 | 4.71875 | 5 | # Scripts : mass_and_weight
# Description : This program asks the user to enter an object’s mass,
# and then calculates its weight using
# weight = mass * acceleration due to gravity.
# If the object weighs more than 1,000 newtons,
# it displays a message indicating that it is too heavy.
# If the object weighs less than 10 newtons,
# it display a message indicating that it is too light.
# Programmer : William Kpabitey Kwabla
# Date : 19.05.16
# Declaring gravity,maximum and minimum weight as Constants and assigning values to them.
ACCELERATION_DUE_TO_GRAVITY = 9.8
MAXIMUM_WEIGHT = 1000
MINIMUM_WEIGHT = 10
# Defining the main function
def main():
print("This program asks the user to enter an object’s mass,")
print("and then calculates its weight using")
print("weight = mass * acceleration due to gravity.")
print("If the object weighs more than 1,000 newtons,")
print("it displays a message indicating that it is too heavy.")
print("If the object weighs less than 10 newtons,")
print("it display a message indicating that it is too light.")
print()
# Asking User to enter object's mass and assigning to the Mass variable.
mass = float(input("Please Enter the Mass of the Object: "))
print()
# Calculating Objects weights using weight = mass * acceleration due to gravity.
weight = mass * ACCELERATION_DUE_TO_GRAVITY
print("The weight of the object is", weight,"Newton")
print()
# Determining whether the object is heavier or light in this manner.
if weight > MAXIMUM_WEIGHT or weight < MINIMUM_WEIGHT:
print("Object is too heavy ")
else:
print("Object is too light ")
# Calling the main function.
main()
| true |
5086ee66505c76e27be7738c6022065c451771bb | Williano/Solved-Practice-Questions | /MultiplicationTable.py | 2,041 | 4.3125 | 4 | # Script: MultiplicationTable.py
# Description: This program ask for a number and limit and generates
# multiplication table for it.
# Programmer: William Kpabitey Kwabla
# Date: 20.07.16
# Defines the main function.
def main():
# Calls the intro function
intro()
# Declares variable for repeating the loop.
keep_going = 'Y' or 'y'
# Loop for asking user for another input.
while keep_going == 'Y' or keep_going == 'y':
print()
# Asks user for the limit
limit = int(input("\t\t\tPlease Enter the limit you want to display to: "))
# Asks user for the number
number = int(input("\t\t\tPlease Enter the number you want to display the multiplication table of : "))
print()
# Displays the heading.
print("\t\t\t\t\t\tMultiplication of ", number)
print("\t\t\t\t\t************************************")
# Calls the multiplication function.
multiplication(limit, number)
# Asks User if he/she wants to check for another number.
keep_going = input("\t\t\tDo you want to check for another number ? Yes = y or Y No = N or n: ")
# Defines the intro function to display what the program does.
def intro():
print("\t\t\t*********************************************************")
print("\t\t\t*\tThis program ask for a number and limit and \t*")
print("\t\t\t*\tgenerates multiplication table for it. \t*")
print("\t\t\t*********************************************************")
# Defines the multiplication function and using the num_limit and number_choice as parameter variables.
def multiplication(num_limit, number_choice):
# Loops and displays the multiplication table
for num in range( num_limit + 1 ):
ans = num * number_choice
print('\t\t\t\t\t\t', num, "X", number_choice, "=" ,ans)
print()
# Calls the main function.
main()
| true |
596e39993129339fa272c671b82d43c35ccaf17e | Akarshit7/Python-Codes | /Coding Ninjas/Conditionals and Loops/Sum of even & odd.py | 284 | 4.15625 | 4 | # Write a program to input an integer N
# and print the sum of all its even
# digits and sum of all its odd digits separately.
N = input()
total = 0
evens = 0
for c in N:
c = int(c)
total += c
if c % 2 == 0:
evens += c
odds = total - evens
print(evens, odds)
| true |
c2bd3cbe9df4bb5ce621a2acc22bcc30b0d8628d | Akarshit7/Python-Codes | /Coding Ninjas/Conditionals and Loops/Check number.py | 295 | 4.15625 | 4 | """
Given an integer n, find if n is positive, negative or 0.
If n is positive, print "Positive"
If n is negative, print "Negative"
And if n is equal to 0, print "Zero".
"""
n=int(input())
if n>=1:
print("Positive")
elif n == 0:
print("Zero")
elif n<=1:
print("Negative")
| false |
4dfe380f00ab58f5741096abaf9493e869792cef | kelvDp/CC_python-crash_course | /chapter_5/toppings.py | 2,546 | 4.4375 | 4 | requested_topping = 'mushrooms'
# checks inequality: so if the req_topping is NOT equal to anchovies, then it will print the message
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# you can check whether a certain value is in a list, if it is the output will be true, and if not --> false:
more_toppings = ['mushrooms', 'onions', 'pineapple']
# so you can ask :
# "mushrooms" in more_toppings -->true because it is in the list
# "pepperoni" in more_toppings --> false
# you can use multiple if statements to test multiple conditions :
more_requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in more_requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in more_requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in more_requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
# this checks to see whether all checks passes whereas if you used elif etc it will stop running after one test passes.
# Checking for special items:
toppings = ['mushrooms', 'green peppers', 'extra cheese']
for topping in toppings:
print(f"Adding {topping}.")
print("\nFinished making your pizza!")
# But what if the pizzeria runs out of green peppers? An if statement inside
# the for loop can handle this situation appropriately:
for topping in toppings:
if topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print(f"Adding {topping}.")
print("\nFinished making your pizza!")
# Checking that a list is not empty :
just_more_toppings = [] #if empty --> false , if full --> true
if just_more_toppings: #if there are items in list
for requested_topping in just_more_toppings:
print(f"Adding {requested_topping}.") #loop through and print toppings
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?") #if list empty (it is) then it will ask if the person wants a plain pizza
# Using multiple lists:
available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']
requested_toppings_list = ['mushrooms', 'french fries', 'extra cheese']
# this will loop through both lists and check to see if items in the one are in the other
for requested_topping in requested_toppings_list:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")
| true |
630e926f49514037051c98cded41250dc8c12f11 | kelvDp/CC_python-crash_course | /chapter_10/word_count.py | 929 | 4.4375 | 4 | def count_words(file):
"""Counts the approx number of words in a file"""
try:
with open(file,encoding="utf-8") as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, but this file {file} does not exist here...")
else:
words = contents.split()
num_words = len(words)
print(f"The file {file} has about {num_words} words.")
file_name = "alice.txt"
count_words(file_name)
# In the previous example, we informed our users that one of the files was
# unavailable. But you don’t need to report every exception you catch.
# Sometimes you’ll want the program to fail silently when an exception occurs
# and continue on as if nothing happened. To make a program fail silently,
# you write a try block as usual, but you explicitly tell Python to do nothing in
# the except block. Python has a pass statement that tells it to do nothing in a
# block.
| true |
17c8acde979e31854089ac390484e05079ebdbca | kelvDp/CC_python-crash_course | /chapter_6/TIY_6-11.py | 637 | 4.3125 | 4 | cities = {
"New York":{"country": "America", "population": 5000000, "fact": "Bill de Blasio is the mayor"},
"Amsterdam": {"country": "Netherland", "population": 850000, "fact": "Houses the Van Gogh Museum"},
"Johannesburg": {"country": "South Africa", "population": 957000, "fact": "Was home to Nelson Mandela"}
}
for city,information in cities.items():
print(f"Here are some facts about {city} :")
country = f"{information['country']}"
population = f"{information['population']}"
fact = f"{information['fact']}"
print(f"This city is found in {country}, it has a population of {population} and a fact about it : {fact}") | false |
fcefa167431b4e2efd08e9f95b43fb57cf3bd37b | kelvDp/CC_python-crash_course | /chapter_2/hello_world.py | 469 | 4.5 | 4 | #can simply print out a string without adding it to a variable:
#print("Hello Python World!")
#or can assign it to a variable and then print the var:
message= "Hello Python world!"
print(message)
#can print more lines:
message_2="Hello Python crash course world!!"
print(message_2)
#code that generates an error :
# another_message="This is another message"
# print(nother_mesage) #this will create an error because the variable name in the print is misspelled.
| true |
59cdb01876a7669b21e7d9f71920850a2a88091c | kelvDp/CC_python-crash_course | /chapter_3/cars.py | 919 | 4.75 | 5 | cars = ['bmw', 'audi', 'toyota', 'subaru']
#this will sort the list in alphabetical order but permanently, so you won't be able to sort it back:
cars.sort()
print(cars)
# You can also sort this list in reverse alphabetical order by passing the
# argument reverse=True to the sort() method. The following example sorts the
# list of cars in reverse alphabetical order:
cars.sort(reverse=True)
print(cars)
print("\n")
#you can sort the list values only for printing/output without changing the list permanently by using sorted instead of sort:
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
print("\n")
#you can reverse a list with the reverse method:
print(cars)
cars.reverse() #this also changes list permanently , but can just apply reverse again if you want normal list
print(cars)
print("\n")
| true |
9a6c01e73c78e5c039f7b4af55924e22b1d4ca85 | kelvDp/CC_python-crash_course | /chapter_4/dimensions.py | 542 | 4.21875 | 4 | dimensions = (200, 50)
#tuples are basically same as lists but they are immutable which means you can't change them without re-assigning the whole thing
print(dimensions[0])
print(dimensions[1])
print("\n")
#!!! cant do this : dimensions[0] = 250 !!!
#you can loop through them just like a list
#this is how to change a tuple:
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
print("\n")
#new tuple:
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension) | true |
906a57cb5b9813652c9d66960ab30f157c769421 | kelvDp/CC_python-crash_course | /chapter_10/write_message.py | 1,615 | 4.84375 | 5 | # To write text to a file, you need to call open() with a second argument telling
# Python that you want to write to the file.
filename = "programming.txt"
with open(filename,"w") as file_object:
file_object.write("I love programming!")
# The second
# argument, 'w', tells Python that we want to open the file in write mode.
# You
# can open a file in read mode ('r'), write mode ('w'), append mode ('a'), or a mode
# that allows you to read and write to the file ('r+').
# It opens in read mode automatically if you don't pass in an argument.
# The open() function automatically creates the file you’re writing to if it
# doesn’t already exist.
# Be careful opening a file in write mode ('w')
# because if the file does exist, Python will erase the contents of the file before
# returning the file object.
# The write() function doesn’t add any newlines to the text you write. So if you
# write more than one line without including newline characters, your file may
# not look the way you want it to.
# ----------APPENDING TO A FILE------------
# If you want to add content to a file instead of writing over existing content,
# you can open the file in append mode. When you open a file in append mode,
# Python doesn’t erase the contents of the file before returning the file object.
# Any lines you write to the file will be added at the end of the file. If the file
# doesn’t exist yet, Python will create an empty file for you.
with open(filename,"a") as f:
f.write("I also love finding meaning in large datasets. \n")
f.write("I love creating apps that can run in a browser.\n")
| true |
8f732d671d158a32dfa7e691f588bef489b74ae8 | beffiom/Learn-Python-The-Hard-Way | /ex6.py | 1,204 | 4.71875 | 5 | # initializing a variable 'types_of_people' as an integer
types_of_people = 10
# initializing a variable 'x' as a formatted string with an embedded variable
x = f"There are {types_of_people} types of people."
# initializing a variable 'binary' as a string
binary = "binary"
# initializing a variable 'do_not' as a string
do_not = "don't"
# initializing a variable 'y' as a formatted string with two embedded variables
y = f"Those who know {binary} and those who {do_not}."
# printing x
print(x)
# printing y
print(y)
# printing a formatted string with embedded variable x
print(f"I said: {x}")
# printing a formatted string with embedded variable y
print(f"I also said: '{y}'")
# initializing a variable 'hilarious' as binary value False
hilarious = False
# initializing a variable 'joke_evualation' as a string
joke_evaluation = "Isn't that joke so funny?! {}"
# printing joke_evaluation formatted with hilarious as an embedded variable
print(joke_evaluation.format(hilarious))
# initializing a variable 'w' as a string
w = "This is the left side of..."
# initializing a variable 'e' as a string
e = "a string with a right side."
# printing a concatenated string combining 'w' and 'e'
print(w+e)
| true |
cd1e137d53325fcd2f7084654877b0c10646ae40 | sitaramsawant2712/Assessment | /python-script/problem_1_solution_code.py | 926 | 4.34375 | 4 | """
1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
(Answer: 233168) (solution code attached: problem_1_solution_code.py)
"""
def natural_number_multi_three_and_five(lower, upper):
'''
@description : Calculate the sum of all the multiples of 3 or 5 as per given param.
'''
sum_of_multiple = 0
for i in range(lower, upper):
if (i % 3 == 0) or (i % 5 == 0):
sum_of_multiple += i
return sum_of_multiple
if __name__ == '__main__':
lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper range limit:"))
sum_of_multiple = natural_number_multi_three_and_five(lower, upper)
output = "Sum of all the multiples of 3 or 5 below {0}. \n(Answer : {1})".format(upper, sum_of_multiple)
print(output)
| true |
1e19e559c0b05629da03e82dacaf3bf925aa9d7e | kundanjha1076/new-python-cours | /string.py | 232 | 4.1875 | 4 | name="kundan "
age=19
print("hello {} your age is {}".format(name,age))#.format method
#f method
print(f"hello {name} your age is {age}")
print(len(name))
x="kundan kumar jha"
y=x.upper()
print(y)
a="kundan kumar jha"
print(a.replace("kundan","kiran")) | false |
cc7a50c93dded63e648a1e0f3c627cf0e490b207 | OngZhenHui/Sandbox_Prac3 | /ascii_table.py | 1,054 | 4.1875 | 4 | def main():
character = str(input("Enter a character: "))
print("The ASCII code for {} is {}".format(character, ord(character)))
lower_limit = 33
upper_limit = 127
number = get_number(lower_limit, upper_limit)
print("The character for {} is {}".format(number, chr(number)))
for i in range(lower_limit, upper_limit + 1):
print("{0:>5} {1:>5}".format(i, chr(i)))
print("How many columns do you want to print?")
upper_limit = lower_limit + int(input(">>>"))
for i in range(lower_limit, upper_limit):
print("{0:>5} {1:>5}".format(i, chr(i)))
def get_number(lower_limit, upper_limit):
valid = False
while valid == False:
try:
number = int(input("Enter a number between 33 to 127: "))
if number < lower_limit or number > upper_limit:
print("Invalid number; number is out of range")
else:
valid = True
except ValueError:
print("Invalid input; input is not an integer")
return number
main() | true |
d9d43b943dd3dd38d8c0584f1fac139ad181b38c | aJns/cao19 | /E4/ex04_01.py | 1,970 | 4.21875 | 4 | """
This coding exercise involves checking the convexity of a piecewise linear function.
You task is to fill in the function "convex_check".
In the end, when the file is run with "python3 ex04_01.py" command, it should display the total number of convex functions.
"""
# basic numpy import
import numpy as np
import time
import matplotlib.pyplot as plt
# random seed fix, do not change this
np.random.seed(0)
initial_func_val = 0 # initial function value which is f(0)=0
# this creates an array of slopes to be checked
slopes_array = np.random.randint(10, size=(100, 5))
# each row within slopes array represents the sequence of slopes m_i's
# m_i represents the slope within the interval (t_i,t_{i+1})
# for example: m_1 = slopes[0] is the slope within [a,t_1]
# List of 5 Break points
# a = t_1 = 0, t_2 = 20, t_3 = 40, t_4 = 60, b = t_5 = 100
# we collect all the points into the following list
break_points = [0, 20, 40, 60, 80, 100]
# Helpful for visualization
def plot_function(slopes, break_points):
x = np.array(break_points)
y = np.array([x[0]])
for i in range(len(slopes)):
new_y = y[i] + slopes[i] * (x[i + 1] - x[i])
y = np.append(y, new_y)
plt.plot(x, y)
plt.show()
def convex_check(slopes, break_points):
"""Checks if the function is convex or not.
Arguments:
slopes {np.array} -- List of Slopes
break_points {np.array} -- List of Breakpoints
"""
convexity = True
# If the slope is smaller than the last one, the function is non-convex
prev_slope = slopes[0]
for slope in slopes[1:]:
if slope < prev_slope:
convexity = False
break
else:
prev_slope = slope
return convexity
convex_func_count = 0
for slopes in slopes_array:
if convex_check(slopes, break_points):
convex_func_count += 1
else:
pass
print('Number of convex functions: ', convex_func_count)
| true |
ca00bc72743cb5168f449a4e7032d3cfdcb884c4 | mikeykh/prg105 | /13.1 Name and Address.py | 2,405 | 4.25 | 4 | # Write a GUI program that displays your name and address when a button is clicked (you can use the address of the school). The program’s window should appear as a sketch on the far left side of figure 13-26 when it runs. When the user clicks the Show Info button, the program should display your name and address as shown in the sketch on the right of the figure.
import tkinter
class MyGUI:
def __init__(self):
# Create main window
self.main_window = tkinter.Tk()
# Create StringVar objects to display name,
# street, and city-state-zip
self.name_value = tkinter.StringVar()
self.street_value = tkinter.StringVar()
self.csz_value = tkinter.StringVar()
# Create two frames
self.info_frame = tkinter.Frame(self.main_window)
self.button_frame = tkinter.Frame(self.main_window)
# Create the label widgets associated with the StringVar objects
self.name_label = tkinter.Label(self.info_frame,
textvariable=self.name_value)
self.street_label = tkinter.Label(self.info_frame,
textvariable=self.street_value)
self.csz_label = tkinter.Label(self.info_frame,
textvariable=self.csz_value)
# Pack the labels
self.name_label.pack()
self.street_label.pack()
self.csz_label.pack()
# Create two buttons
self.show_info_button = tkinter.Button(self.button_frame,
text='Show Info',
command=self.show)
self.quit_button = tkinter.Button(self.button_frame,
text='Quit',
command=self.main_window.destroy)
# Pack the buttons
self.show_info_button.pack(side='left')
self.quit_button.pack(side='right')
# Pack the frames
self.info_frame.pack()
self.button_frame.pack()
# Enter the tkinter main loop
tkinter.mainloop()
# Callback function for the Show Info button
def show(self):
self.name_value.set('Michael Harris')
self.street_value.set('8900 US-14')
self.csz_value.set('Crystal Lake, IL 60012')
# Create an instance of the MyGUI class
my_gui = MyGUI()
| true |
a2f82639d7a3d84317e5d0c3bfe6e5d8b9ea91dc | mikeykh/prg105 | /Automobile Costs.py | 2,135 | 4.59375 | 5 | # Write a program that asks the user to enter the
# monthly costs for the following expenses incurred from operating
# his or her automobile: loan payment, insurance, gas, oil, tires and maintenance.
# The program should then display the total monthly cost of these expenses,
# and the total annual cost of these expenses.
# Assign meaningful names to your functions and variables.
# Every function also needs a comment explaining
# what it does and what other function it works with.
# Function 1:
# Gather information from user
# Accumulate the total in a local variable
# Print the monthly costs on screen, formatted appropriately for money
# Pass the monthly cost to Function 2
# Function 2:
# Accepts a float parameter
# Calculates yearly cost by multiplying monthly cost by 12
# Displays the yearly cost on screen, formatted appropriately for money
def calculate_total_monthly_cost():
# This function is used to gather all of the information,
# adds all of the users inputs and sets the sum to a variable,
# passes the variable to the function calculate_total_yearly_cost,
# and calls the function calculate_total_monthly_cost.
loan = float(input("Please enter your car payment: "))
insurance = float(input("Please enter your the amount of your insurance payment: "))
gas = float(input("Please enter your monthly gas expense: "))
oil = float(input("Please enter your monthly oil expense: "))
tire = float(input("Please enter your monthly expense for tires: "))
maintenance = float(input("Please enter your monthly maintenance expense: "))
total_monthly_cost = loan+insurance+gas+oil+tire+maintenance
print("This is the total monthly cost: $", format(total_monthly_cost, ",.2f"), sep="")
calculate_total_yearly_cost(total_monthly_cost)
def calculate_total_yearly_cost(total_monthly_cost):
# This function calculates and prints the total yearly cost
# and is called by the function calculate_total_monthly_cost.
yearly_total = total_monthly_cost * 12
print("This is the yearly cost: $", format(yearly_total, ',.2f'), sep="")
calculate_total_monthly_cost()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.