blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
dcd1210f411cb0d8f34303f0063758fd1c3644f2 | elzbietamal95/Python-tutorial | /Final_Exam/FinalExam_Problem4.py | 683 | 4.15625 | 4 | def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
item = 0
maksimum = 0
for element in t:
if type(element) == tuple or type(element) == list:
recursively_maksimum = max_val(t[item])
if recursively_maksimum > maksimum:
maksimum = recursively_maksimum
elif type(element) == int:
if element > maksimum:
maksimum = element
item += 1
return maksimum
print(max_val(([5], 12, (1,2, [67, [[4,[100]]]]), [[1],[9]])))
| true |
944ff8b05be2cd942fbee63d34720b9d64d21e21 | kaushik853/lpthw_python_3 | /zed-python/ex3.py | 653 | 4.4375 | 4 | print('i will now count my chickens')
# this is for counting chickens
print('hens',25.0+30/5) # first we will divide 30 with 5 and then add 25 to it
print('roosters' , 100 - 25 * 3 % 4)# first we multiply 25 with 3 and then we take modulo of 4 and substract by 100
print('Now i will count the eggs')
print(3+2+1-5+4%2-1.0/4+6)
print('is it true that 3+2<5-7?')
print(3+2<5-7)
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
# this is comment
print("Oh, that's why it's False.")
print("How about some more.")
# another comment
print("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)
| true |
7083e82841abb8c6fb3956e5303a19996b7c5423 | fabioarnoni/python-journey | /ex39_sorting_lists.py | 353 | 4.28125 | 4 | # Sorting Lists
numbers = [2, 4, 6, 8, 1, 3, 5, 7, 9]
another_numbers = numbers
print(numbers)
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)
print(another_numbers)
# What happened above? Learn more about mutable and immutable objects here:
# https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747
| true |
22c813685110464b249439ce49e799116df404a6 | ivand200/Coursera_Python_for_everybody | /lists_08.py | 2,690 | 4.59375 | 5 | # Exercise 4: Find all unique words in a file
# List all unique words, sorted in
# alphabetical order, that are stored in a file romeo.txt containing a subset of Shakespeare’s work.
# To get started, download a copy of the file www.py4e.com/code3/romeo.txt.
# Create a list of unique words, which will contain the final result.
# Write a program to open the file romeo.txt and read it line by line. For each line,
# split the line into a list of words using the split function.
# For each word, check to see if the word is already in the list of unique words.
# If the word is not in the list of unique words, add it to the list. When the program completes,
# sort and print the list of unique words in alphabetical order.
file = input("Enter a file name:")
if len(file) < 1 : file = "romeo.txt"
fhand = open(file, "r")
lst = list()
for row in fhand:
rows = row.split()
for words in rows:
if words in lst:
continue
else:
lst.append(words)
lst.sort() # lst.sort(reverse=True)
print(lst)
# Exercise 5: Minimalist Email Client. Emails are separated by a special line
# which starts with From (notice the space). Importantly, lines starting with
# From: (notice the colon) describes the email itself and does not act as a
# separator. Imagine you wrote a minimalist email app, that lists the email
# of the senders in the user’s Inbox and counts the number of emails.
# Write a program to read through the mail box data and when you find line
# that starts with “From”, you will split the line into words using
# the split function. We are interested in who sent the message,
# which is the second word on the From line.
file = input("Enter a file name:")
if len(file) < 1 : file = "mbox.txt"
fhand = open(file, "r")
lst = list()
count = 0
for rows in fhand:
if rows.startswith("From "):
row = rows.split()
count = count + 1
if row[1] in lst:
continue
else:
lst.append(row[1])
print("There were", count, "lines in the doc")
# Exercise 6: Rewrite the program that prompts the user for a list of numbers and
# prints out the maximum and minimum of the numbers at the end when the user
# enters “done”. Write the program to store the numbers the user enters in a list
# and use the max() and min() functions to compute the maximum and minimum numbers
# after the loop completes.
lst = list()
while True:
score = input("Enter a number:")
if score == "done":
break
try:
score_ = int(score)
lst.append(score_)
print(score_)
except:
print("Enter a number plaese!")
print("Maximum:", max(lst), "Minimum:", min(lst))
| true |
803e766b2b4851a8ab8aaeb21b6ebc0826eed3e0 | starkworld/CodeSignals-Practice | /minesweeper.py | 1,628 | 4.125 | 4 | """In the popular Minesweeper game you have a board with some mines and those cells that don't contain a mine have a
number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of
mines we want to create a Minesweeper game setup.
Example
For matrix = [[true, false, false],
[false, true, false],
[false, false, false]] the output should be
minesweeper(matrix) = [[1, 2, 1],
[2, 1, 1],
[1, 1, 1]]
"""
def neighbors(matrix, i, j, row, col):
mine = 0
if not ((i < 1) or (j < 1)):
if matrix[i - 1][j - 1]:
mine += 1
if not (i < 1):
if matrix[i - 1][j]:
mine += 1
if not ((i < 1) or (j >= col - 1)):
if matrix[i - 1][j + 1]:
mine += 1
if not (j >= col - 1):
if matrix[i][j + 1]:
mine += 1
if not ((i >= row - 1) or (j >= col - 1)):
if matrix[i + 1][j + 1]:
mine += 1
if not (i >= row - 1):
if matrix[i + 1][j]:
mine += 1
if not ((i >= row - 1) or (j < 1)):
if matrix[i + 1][j - 1]:
mine += 1
if not (j < 1):
if matrix[i][j - 1]:
mine += 1
return mine
def minesweeper(matrix):
row = len(matrix)
col = len(matrix[0])
sol = []
for i in range(0, row):
temp = []
for j in range(0, col):
temp.append(neighbors(matrix, i, j, row, col))
sol.append(temp)
return sol
print(minesweeper([[False, False, False],
[False, False, False]]))
| true |
00eaf04753d641528c6b9f46e8b107951a6f6f23 | omarKaushru/Python-Basic | /Recursion/main.py | 1,622 | 4.28125 | 4 | """"
# ‘To understand recursion, you must first understand recursion’
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(4))
# sum of n number using for loop
def sum_f(n):
sum = 0
for i in range(1, n + 1):
sum = sum + i
return sum
# sum of n number using recursion technique
def sum_r(n):
print(n)
if n == 1:
return 1
return n + sum_r(n - 1)
print('Sum of n number using loop', sum_f(5000))
print('Sum of n number using recursion', sum_r(100))
# reversing a list using loop
def reverser_l(list):
new_list = []
for i in range(0, len(list)):
new_list.append(0)
for i in range(len(list) - 1, -1, -1):
new_list[len(list) - 1 - i] = list[i]
return new_list
def reverse_r(list):
if len(list) == 0:
return []
return [list[-1]] + reverse_r(list[:-1])
list = [1, 2, 3, 4, 5]
print(reverser_l(list))
print(reverse_r(list))
"""
def summation(num_list):
if len(num_list) == 0:
return 0
if num_list[-1] % 2 == 0:
return num_list[-1] + summation(num_list[:-1])
else:
return summation(num_list[:-1])
a = summation([1, 2, 3, 4, 6, 10, 11, 121, 1009])
print(a)
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
for i in range(0, 5):
print(fib(i), end=" ")
l = []
def convert_number(num):
if num == 0:
return l
digit = num % 2
l.append(digit)
convert_number(2)
convert_number(6)
l.reverse()
for i in l:
print(i, end=" ")
| false |
9c2c3be4fd37b3bf648bbb96e241c15a7bb1c230 | Bradley94/misc-theory-work | /sorting_lists_with_comprehension.py | 1,962 | 4.34375 | 4 | '''
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
**********************************************************************
Sample tests
Test.assert_equals(sort_array([5, 3, 2, 8, 1, 4]), [1, 3, 2, 8, 5, 4])
Test.assert_equals(sort_array([5, 3, 1, 8, 0]), [1, 3, 5, 8, 0])
Test.assert_equals(sort_array([]),[])
**********************************************************************
'''
def sort_array(source_array):
if source_array == []:
return source_array
sorted_odds = sorted([n for n in source_array if n % 2])
new_list = []
for n in source_array:
if n % 2:
new_list.append(sorted_odds.pop(0))
else:
new_list.append(n)
return list(new_list)
'''
BETTER SOLUTIONS/PRACTICES
-----------------------------------------------------------
def sort_array(arr):
odds = sorted((x for x in arr if x % 2 != 0), reverse=True)
return [x if x % 2 == 0 else odds.pop() for x in arr]
-----------------------------------------------------------
def sort_array(source_array):
odds = iter(sorted(v for v in source_array if v % 2))
return [next(odds) if i % 2 else i for i in source_array]
-----------------------------------------------------------
def sort_array(source_array):
odds = []
answer = []
for i in source_array:
if i % 2 > 0:
odds.append(i)
answer.append("X")
else:
answer.append(i)
odds.sort()
for i in odds:
x = answer.index("X")
answer[x] = i
return answer
-----------------------------------------------------------
''' | true |
9c6162cfa98221f3183ea664acd21dd7506207bd | Bradley94/misc-theory-work | /Codewars/level6/highest_scoring_word.py | 1,330 | 4.1875 | 4 | """
Given a string of words, you need to find the highest scoring word.
Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.
You need to return the highest scoring word as a string.
If two words score the same, return the word that appears earliest in the original string.
All letters will be lowercase and all inputs will be valid.
"""
def high(x):
listed_words = x.split()
word_values = []
for word in listed_words:
value = 0
for letter in word:
value += ord(letter) - 96
word_values.append(value)
#print(listed_words)
#print(word_values)
word_index = word_values.index(max(word_values)) # No failsafe to ensure first largest value is implemented as not sure
# how to do this yet. All random tests work fine so I'm assuming/hoping
# that the index(max) function always returns the first largest index pos.
#print(word_index)
return listed_words[word_index]
"""
test.assert_equals(high('man i need a taxi up to ubud'), 'taxi')
test.assert_equals(high('what time are we climbing up the volcano'), 'volcano')
test.assert_equals(high('take me to semynak'), 'semynak')
"""
| true |
96fcaa30ca2274b432537b18f3dcce440324f728 | Bradley94/misc-theory-work | /Codewars/level6/format_list_of_names.py | 1,647 | 4.1875 | 4 | """
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names,
which should be separated by an ampersand.
Example:
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])
# returns 'Bart & Lisa'
namelist([ {'name': 'Bart'} ])
# returns 'Bart'
namelist([])
# returns ''
Note: all the hashes are pre-validated and will only contain A-Z, a-z, '-' and '.'.
"""
def namelist(names):
just_names = []
# Get a list of just the names, no keys
for name in names:
just_names += name.values()
# Create string with every name but the last
count = 0
txt = ''
for name in just_names:
if count == 0:
txt += name
count += 1
elif count == len(just_names) - 1:
txt += " & " + name
else:
txt += ", " + name
count += 1
return txt
"""
Test.assert_equals(namelist([{'name': 'Bart'},{'name': 'Lisa'},{'name': 'Maggie'},{'name': 'Homer'},{'name': 'Marge'}]), 'Bart, Lisa, Maggie, Homer & Marge',
"Must work with many names")
Test.assert_equals(namelist([{'name': 'Bart'},{'name': 'Lisa'},{'name': 'Maggie'}]), 'Bart, Lisa & Maggie',
"Must work with many names")
Test.assert_equals(namelist([{'name': 'Bart'},{'name': 'Lisa'}]), 'Bart & Lisa',
"Must work with two names")
Test.assert_equals(namelist([{'name': 'Bart'}]), 'Bart', "Wrong output for a single name")
Test.assert_equals(namelist([]), '', "Must work with no names")
"""
| true |
709899922a590fad10bfb1299eba107935b12f5c | bmolina-nyc/ByteAcademyWork | /Week1/Week1Day2/1-core-functions/1-core-functions_answers.py | 986 | 4.34375 | 4 | # print() # and the file, end, and sep parameters
# input()
''' input() prompts the user to enter a value - the value is always a string
The value will be saved to a variable you assigned to it
my_var = input("give me a number") # user enters 5
print(my_var) # console prints 5
type(my_var) # the 5 is from the str class
'''
# # the .is methods of strings (isalpha() isalnum() etc)
'''
these functions allow a user to check if a character is of the types a-z
or A-Z (for isalpha() or also 0-9 (for isalnum()).
This is very useful if you wanted to filter out only these specific characters and
nothing else when parsing a string or just to check if the string is of the types
listed above.
str_a = "this is not alphanumeric cause there are spaces"
print(str_a.isalnum()) # returns False
str_b = "alphastring"
print(str_b.isalpha()) # returns True
str_c ="abc123"
print(str_c.isalnum()) # returns True
'''
# math.isclose() # look at (.1 + .2) == .3
# round()
# len()
# sum() | true |
c2e37b05eb804d33361f90de779ed7ead5576d63 | bmolina-nyc/ByteAcademyWork | /Week1/Week1Day2/4-mcnugget-numbers/SAMPLE_mcnugg.py | 503 | 4.15625 | 4 |
def mcnugg(x):
"""This is what the function does
input: x, a number (integer)
output: mcnugget numbers up to x
"""
mcnumbs=[0]
i=1
not_nug=[]
while i<=x:
if i-6 in mcnumbs or i-9 in mcnumbs or i-20 in mcnumbs:
mcnumbs.append(i)
i+=1
else:
i+=1
for num in range(0,i):
if num not in mcnumbs:
not_nug.append(num)
return mcnumbs
value = int(input('Choose a number: '))
print(mcnugg(value))
| true |
4416973e380ae27f183c029c4ccd7c19743843a2 | SkeyLearing/Python3 | /DataStructure/fillter_data.py | 766 | 4.25 | 4 | # 常用的数据解析
from random import randint
'''
列表:随机生成10个 -10~10 之间的数,提取出正数
·过滤负数: filter() 与 列表解析
·列表解析的速度要高于 filter()
'''
list = [randint(-10, 10) for _ in range(10)]
print("filter函数:", filter(lambda x: x >= 0, list))
print("列表解析:", [x for x in list if x >= 0])
'''
字典:随机生成20个学生的成绩,提取出大于90分的数据
·字典解析
'''
dict = {x: randint(60, 100) for x in range(1, 21)}
print("字典解析:", {k: v for k, v in dict.items() if v > 90})
'''
集合:提取出能被3整除的数据
·集合解析
'''
coll = {-5, -3, 2, 5, 6, 7, 8, 9}
print("集合解析:", {x for x in coll if x % 3 == 0}) | false |
0d7fa1a40eba1271ff4737dfc43c3df9b904a8d7 | MarcoDSilva/MIT6001x-Introduction-to-Computer-Science-and-Programming-in-Python | /week3/oddTuples.py | 545 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 17 20:09:31 2020
Write a procedure called oddTuples, which takes a tuple as input,
and returns a new tuple as output, where every other element
of the input tuple is copied, starting with the first one.
@author: MarcoSilva
"""
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
odd = ()
for x in range(0,len(aTup)):
if x % 2 == 0:
odd = odd + (aTup[x],)
return odd
| true |
8f39804d906d1f931625de09ff33d59945348dea | qnomon/Python-Studies | /ex072.py | 329 | 4.1875 | 4 | extenso = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'Treze','Quatorze', 'Quinze', 'Dezesseis', 'Dezessete', 'Dezoito', 'Dezenove', 'Vinte')
n = 22
while n < 0 or n > 20:
n = int(input('Digite um número: '))
print(f'O numero que você digitou foi {extenso[n]}') | false |
d2bd196b4fb3f3ba0d708faea229499c31bbd3c5 | Captain02/LearningNotes | /python/code/lesson_05/10.装饰器.py | 2,983 | 4.375 | 4 | # 创建几个函数
def add(a, b):
'''
求任意两个数的和
:param a:
:param b:
:return:
'''
r = a + b
return r
def mul(a, b):
'''
求任意两个数的积
:param a:
:param b:
:return:
'''
r = a * b
return r
# 希望函数可以在计算前,打印开始计算,计算结束后打印计算完毕
# 我们可以直接通过修改函数中的代码来完成这个需求,但是会产生以下一些问题
# 1.如果要修改的函数过多,修改起来比较麻烦
# 2.并且不方便后期的维护
# 3.并这样做会违反开闭原则(OCP)
# 程序的设计,需要开发对程序的扩展,需要关闭对程序的修改
r = add(123, 345)
# print(r)
# 我们希望在不修改原函数的情况下,来对函数进行扩展
def fn():
print('我是fn函数....')
def fn2():
print('函数开始执行!!')
fn()
print('函数执行完毕!!')
def new_add(a, b):
print('计算开始~~~')
r = add(a, b)
print('计算结束~~~')
return r
r = new_add(111, 222)
print(r)
# 上边的方式,已经可以在不修改源代码的情况下对函数进行扩展了
# 但是,这种方式要求我们每扩展一个函数就要手动创建一个新的函数,实在是太麻烦了
# 为了解决这个问题,我们创建一个函数,让这个函数可以自动的帮助我们生产函数
def begin_end(old):
'''
用来对其他含糊进行扩展,是其他函数可以再执行前打印开始执行,执行后打印执行结束
参数:
old 要扩展的函数对象
:param old:
:return:
'''
# 创建一个新函数
def new_function(*args, **kwargs):
print("开始执行~~~")
# 调用被扩展的函数
result = old(*args, **kwargs)
print('执行结束~~~~')
# 返回函数的执行结果
return result
# 返回新函数
return new_function
f = begin_end(fn)
f2 = begin_end(add)
f3 = begin_end(mul)
r = f()
r = f2(123, 456)
r = f3(123, 456)
print(r)
# 想begin_end这种函数我们就称它为装饰器
# 通过装饰器,可以再不修改原来函数的情况下来对函数进行扩展
# 在开发中,我们都是通过装饰器来扩展函数的功能的
# 在定义函数时,可以通过@装饰器,来使用这种
def fn3(old):
'''
用来对其他函数进行扩展,使其他函数可以在执行前打印开始执行,执行后打印执行结束
:param old:要扩展的函数对象
:return:
'''
# 创建一个新的函数
def new_function(*args, **kwargs):
print('fn3装饰~开始执行~~~~')
# 调用被扩展的函数
result = old(*args, **kwargs)
print('fn3装饰~执行结束~~~~')
# 返回函数的执行结果
return result
# 返回新函数
return new_function
@fn3
@begin_end
def say_hello():
print('大家好~~~~')
say_hello()
| false |
0bbd6d383a16899755fa58f0c3db49aad6089ced | Patrickm79/cs-module-project-recursive-sorting | /src/searching/searching.py | 2,079 | 4.46875 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
# if the starting index is less than the ending index, return -1, exit out
if start > end:
return -1
else:
# This will find the midpoint
mid = (start + end) // 2
# if thar target is equal to the midpoint, then return the midpoint
if target == arr[mid]:
return mid
# if the target is less than the midpoint, we move left
elif target < arr[mid]:
# return the binary search with the midpoint - 1
return binary_search(arr, target, start, mid-1)
else:
# otherwise, we move right, we increase the midpoint + 1
return binary_search(arr, target, mid+1, end)
def descending_binary_search(arr, target, left, right):
# base case
# or we searched the whole array, i.e. when left > right
if left > right:
return -1
# how do we move closer to a base case?
# we'll stop when we either find the target
else:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
# rule out the right side
return descending_binary_search(arr, target, left, mid - 1)
else:
# rule out the left side
return descending_binary_search(arr, target, mid + 1, right)
def agnostic_binary_search(arr, target):
# figure out whether the input array is sorted in ascending or descending order
# keep a boolean to indicate the order of the array
# compare arr[0] and arr[1]
if arr[0] > arr[-1]:
is_ascending = False
else:
is_ascending = True
# if the input array is ascending, call `binary_search` with the array and target
if is_ascending:
return binary_search(arr, target, 0, len(arr) - 1)
# otherwise, call `descending_binary_search` with the array and target
else:
return descending_binary_search(arr, target, 0, len(arr) - 1)
| true |
82832fa1357c7d178c916e1936cdeb4d2de017d8 | smartyaya/Python-Shapely-Examples | /dijkstra.py | 1,767 | 4.1875 | 4 | import sys
def shortestpath(graph,start,end,visited=[],distances={},predecessors={}):
"""Find the shortest path between start and end nodes in a graph"""
# we've found our end node, now find the path to it, and return
if start==end:
path=[]
while end != None:
path.append(end)
end=predecessors.get(end,None)
return distances[start], path[::-1]
# detect if it's the first time through, set current distance to zero
if not visited: distances[start]=0
# process neighbors as per algorithm, keep track of predecessors
for neighbor in graph[start]:
if neighbor not in visited:
neighbordist = distances.get(neighbor,sys.maxint)
tentativedist = distances[start] + graph[start][neighbor]
if tentativedist < neighbordist:
distances[neighbor] = tentativedist
predecessors[neighbor]=start
# neighbors processed, now mark the current node as visited
visited.append(start)
# finds the closest unvisited node to the start
unvisiteds = dict((k, distances.get(k,sys.maxint)) for k in graph if k not in visited)
closestnode = min(unvisiteds, key=unvisiteds.get)
# now we can take the closest node and recurse, making it current
return shortestpath(graph,closestnode,end,visited,distances,predecessors)
if __name__ == "__main__":
graph = {'a': {'w': 14, 'x': 7, 'y': 9},
'b': {'w': 9, 'z': 6},
'w': {'a': 14, 'b': 9, 'y': 2},
'x': {'a': 7, 'y': 10, 'z': 15},
'y': {'a': 9, 'w': 2, 'x': 10, 'z': 11},
'z': {'b': 6, 'x': 15, 'y': 11}}
print shortestpath(graph,'a','b')
"""
Result:
(20, ['a', 'y', 'w', 'b'])
"""
| true |
8169164961b1d8502cc2daeaa3dbc76d0286a7d4 | abijithring/classroom_programs | /34_sets/set_ops.py | 2,725 | 4.40625 | 4 |
# set is the function used to convert any object into set object
x = set("A Python Tutorial")
print(x)
x = set(["Perl", "Python", "Java"])
print(x)
cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))
print(cities)
# adding element to list
cities = set(["Frankfurt", "Basel","Freiburg"])
cities.add("Strasbourg")
print(cities)
#frozensets
cities = frozenset(["Frankfurt", "Basel","Freiburg"])
#cities.add("Strasbourg")
# Other way of defining the set
#We can define sets (since Python2.6) without using the built-in set function.
#We can use curly braces instead:
adjectives = {"cheap","expensive","inexpensive","economical"}
print(adjectives)
# set operations
# add operation
colours = {"red","green"}
colours.add("yellow")
print(colours)
# clear
more_cities = {"Winterthur","Schaffhausen","St. Gallen"}
cities_backup = more_cities.copy()
more_cities.clear()
print(more_cities)
#difference()
x = {"a","b","c","d","e"}
y = {"b","c"}
z = {"c","d"}
print("Difference :",x.difference(y))
print("Difference :",x-y)
print("Difference :",x.difference(y).difference(z))
print("Difference :",x-y-z )
#Instead of using the method difference, we can use the operator "-":
print(x-y)
print(x - y - z)
#The method difference_update removes all elements of another set from this set.
#x.difference_update() is the same as "x = x - y"
x = {"a","b","c","d","e"}
y = {"b","c"}
x.difference_update(y)
print("Elements of x",x)
x = {"a","b","c","d","e"}
y = {"b","c"}
x = x - y
print("After difference update",x)
#discard(el)
#An element el will be removed from the set, if it is contained in the set.
#If el is not a member of the set, nothing will be done.
x = {"a","b","c","d","e"}
x.discard("a")
print("Discard example:",x)
x.discard("z")
print(x)
#remove(el)
#works like discard(), but if el is not a member of the set,
#a KeyError will be raised.
x = {"a","b","c","d","e"}
#x.remove("q")
print("Remove example:",x)
x.remove("b")
print("After removing B ", x)
#intersection(s)
#Returns the intersection of the instance set and the set s as a new set.
#In other words: A set with all the elements which are contained
#in both sets is returned.
x = {"a","b","c","d","e"}
y = {"c","d","e","f","g"}
x = { "c","d","e" ,"d"}
print("Intersection example:",x.intersection(y))
print("Intersection example:",x.intersection(y).intersection(z))
#pop()
x = {"a","b","c","d","e","q"}
print("Pop example",x.pop())
print("Pop example",x.pop())
print("Pop example",x.pop())
print("Pop example",x.pop())
print("Pop example",x.pop())
print(x)
#issubset()
x = {"a","b","c","d","e"}
y = {"c","d"}
print(x.issubset(y)) # false
print(y.issubset(x)) # true
'''
| true |
be18120b4b148c96d2ba8f130705179e706a4270 | clairerhoda/Python-Programs | /lab4_prog5.py | 384 | 4.125 | 4 | #Claire Rhoda
#1068768
#Program 5
#This program highlights the largest number from inputed numbers
def readValues():
key = 'Q'
num_list = []
while key != 'Q':
print("Please enter values, Q to quit")
num = float(input())
num = append(num)
def findLargest():
sort()
reverse()
largest = [0:1]
def display():
def main():
readValues()
| true |
310a0e91a633539dc956b7acf04100e04f0162bf | clairerhoda/Python-Programs | /coffee_program/coffee_file.py | 1,299 | 4.34375 | 4 | #Claire Rhoda
#1068768
#Program 8
#This program allows the user to modify a coffee record.
def main():
answer = 'Y'
while answer.upper() == 'Y':
print("Coffee Menu")
print("------------")
f = open('coffee.txt','r')
file_contents = f.read()
print(file_contents)
f.close()
print("1. Search")
print("2. Delete")
print("3. Show Information")
print("4. Modify")
print("5. Add")
choice = input("Please choose a program from the list above")
if choice == '1':
import search_coffee_records
search_coffee_records.search()
if choice == '2':
import delete_coffee_record
delete_coffee_record.del_coffee()
if choice == '3':
import show_coffee_records
show_coffee_records.show()
if choice == '4':
import modify_coffee_records
modify_coffee_records.mod_coffee()
if choice == '5':
import add_coffee_record
add_coffee_record.add_coffee()
print("Would you like to make any more changes or look up ",end='')
print("another item?")
answer = input("Enter 'y' for yes or anything else for no")
if __name__ == "__main__":
main()
| true |
30470f4df4b89360521da2b90058694befa062e5 | SYESHASWINI/matrix-operations | /operations.py | 1,171 | 4.15625 | 4 | #performing operations on n*n matrix
import numpy as np
x=np.array(input("enter n*n matrix"))
y=np.array(input("enter another n*n matrix"))
print "the matrix x\n", x
print "the matrix y\n",y
add=np.add(x,y)
print "addition of two matrices\n",add
sub=np.subtract(x,y)
print"subtraction of two matrices\n",sub
div=np.divide(x,y)
print "division of two matrices\n",div
mul=np.multiply(x,y)
print"multipilcation of two matrices\n",mul
dot=np.dot(x,y)
print"dot product of two matrices\n",dot
sqrt=np.sqrt(x)
print "sqrt of matrix x\n",sqrt
trans=x.T
print" transpose of matrix y \n",trans
summ=np.sum(y)
print"sum of elements of y\n",summ
sqr=np.square(y)
print" square of matrix y \n",sqr
trac=np.trace(x)
print "trace of matrix x\n",trac
dia=np.diagonal(x)
print "diagonal elements of matrix x\n",trac
rank=np.linalg.matrix_rank(x)
print"rank of matrix x\n",rank
det=np.linalg.det(x)
print"determinant of the matrix\n",det
inverse=np.linalg.inv(x)
print"inverse of matrix x\n",inverse
eig=np.linalg.eig(x)
print "eigen vectors of x \n",eig
eigval=np.linalg.eigvals(x)
print "eigen values of x \n",eigval
power=np.linalg.matrix_power(x,3)
print"power of matrix x\n",power
| true |
ed7c31d7bb0dcf7edb074aba8ed7fc65b5b5e213 | melandres8/machine_learning | /math/0-linear_algebra/3-flip_me_over.py | 314 | 4.1875 | 4 | #!/usr/bin/env python3
# returns the transpose of a 2D matrix
def matrix_transpose(matrix):
"""Transpose of a matrix"""
transpose = []
for i in range(len(matrix[0])):
transpose.append([])
for j in range(len(matrix)):
transpose[i].append(matrix[j][i])
return transpose
| true |
14f19c6acb00a33b0ac728dc0179b22c7ca1f009 | okellogabrielinnocent/data_structure_gab | /2_D_arrays.py | 1,929 | 4.375 | 4 | # 2 D array or a square array (an array of n rows and n columns)
# Two-dimensional arrays are basically array within arrays.
# Here, the position of a data item is accessed by using two indices.
# It is represented as a table of rows and columns of data items.
# array-name = [ [d1, d2, .... dn], [e1, e2, .... en] ]
array_input = [ [10,12,14] ,[0,1,2] ]
print(array_input[0]) # printing elements of row 0
print(array_input[1]) # printing elements of row 1
# Input to a 2-D Array
# Input to a 2-D array is provided in the form of rows and columns.
# Insert size of array eg 2
# insert row
# insert column
# save it in array_input
# with list comprehesion one step
n = int(input())
arr = []
for i in range(n):
arr.append([int(j) for j in input().split()])
print(arr)
# with list comprehesion second step
n = int(input())
a = [[int(j) for j in input().split()] for i in range(n)]
# OR without list comprehension
# the first line of input is the number of rows of the array
n = int(input())
a = []
for i in range(n):
row = input().split()
for i in range(len(row)):
row[i] = int(row[i])
a.append(row)
# Insert to a 2-D array
from array import *
input = [[1,1,1,1], [12,12,12,12]]
input.insert(1, [1,3,5,7,9])
print([y for y in input])
# Procesing 2-D array
# Suppose you are given a square array (an array of n rows and n columns).
# And suppose you have to set elements of the main diagonal equal to 1 (that is, those elements a[i][j] for which i==j),
# to set elements above than that diagonal equal to 0, and to set elements below that diagonal equal to
# - That is, you need to produce such an array (example for n==4):
n = 4
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(n):
if i < j:
a[i][j] = 0
elif i > j:
a[i][j] = 2
else:
a[i][j] = 1
for row in a:
print(' '.join([str(elem) for elem in row]))
| true |
92ba36c3d647c9481493b9a8fa7a804cb225fab2 | okellogabrielinnocent/data_structure_gab | /reverse_array.py | 860 | 4.5 | 4 | # program to reverse an array or string
# method 1
# 1) Initialize start and end indexes as start = 0, end = n-1
# 2) In a loop, swap arr[start] with arr[end] and change start and end as follows :
# start = start + 1, end = end - 1
def reverse_list(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
# method 2
# 1) Initialize start and end indexes as start = 0, end = n-1
# 2) Swap arr[start] with arr[end]
# 3) Recursively call reverse for rest of the array.
def reverseList(arr, start, end):
if start >= end:
return
arr[start], arr[end] = arr[end], arr[start]
reverseList(arr, start+1, end-1)
# Method 3
# Using Python List slicing
def reverse_list_slice(arr):
return( A[::-1])
arr = [1,2,3,4,5,6,7,8,9]
reverse_list(arr, 0,9)
reverseList(arr, 0, 5)
reverse_list_slice()
| true |
5e0b60519289922463a30fc2ff6dc91245b29de7 | kshitij12345/graph-algorithms | /connecting_points.py | 2,128 | 4.40625 | 4 | #Uses python3
import sys
import math
from queue import PriorityQueue
"""
MakeSet(x) initializes disjoint set for object x
Find(x) returns representative object of the set containing x
Union(x,y) makes two sets containing x and y respectively into one set
Some Applications:
- Kruskal's algorithm for finding minimal spanning trees
- Finding connected components in graphs
- Finding connected components in images (binary)
"""
def MakeSet(x):
x.parent = x
x.rank = 0
def Union(x, y):
xRoot = Find(x)
yRoot = Find(y)
if xRoot.rank > yRoot.rank:
yRoot.parent = xRoot
elif xRoot.rank < yRoot.rank:
xRoot.parent = yRoot
elif xRoot != yRoot: # Unless x and y are already in same set, merge them
yRoot.parent = xRoot
xRoot.rank = xRoot.rank + 1
def Find(x):
if x.parent == x:
return x
else:
x.parent = Find(x.parent)
return x.parent
""""""""""""""""""""""""""""""""""""""""""
import itertools
class Vertex:
def __init__ (self, label):
self.label = label
self.parent = None
self.rank = None
def __str__(self):
return self.label
def cost(x,y):
return ((x[0]-x[1])**2 +(y[0]-y[1])**2)**0.5
def minimum_distance(x, y):
Q = PriorityQueue()
result = 0.
a = []
b = []
for i in range(len(x)):
for j in range(i+1,len(x)):
a.append(x[i])
a.append(x[j])
b.append(y[i])
b.append(y[j])
c = cost(a,b)
#print ("cost",c)
Q.put((c,[i,j]))
a = []
b = []
l = [Vertex(ch) for ch in range(len(x))]
[MakeSet(i) for i in l]
while not Q.empty():
q = Q.get()
x = q[1][0]
y = q[1][1]
if Find(l[x]) != Find(l[y]):
Union(l[x],l[y])
result = result + q[0]
return result
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
x = data[1::2]
y = data[2::2]
print("{0:.9f}".format(minimum_distance(x, y)))
| true |
4ca92fade89c24b67ca7395d3c8081fe794dfc0c | OldFuzzier/Data-Structures-and-Algorithms- | /Tree/BinaryTree/101_Symmetric_Tree.py | 1,883 | 4.28125 | 4 | # coding=utf-8
# 101. Symmetric Tree
# 对称二叉树
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# MyWay in-order + 回文双指针检测
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
tempList = [] # store element
def inorder(root):
if not root or not (root.left or root.right):
return
inorder(root.left)
# in-order
tempList.append(str(root.left.val)) if root.left else tempList.append('N')
tempList.append(str(root.right.val)) if root.right else tempList.append('N')
inorder(root.right)
inorder(root)
print tempList
return self.isPalindrome(tempList)
# double pointer
def isPalindrome(self, lst):
i, j = 0, len(lst)-1
while i<j:
if lst[i] == lst[j]:
i += 1
j -= 1
else:
return False
return True
# PCWay
# "and" trickier
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: # border situation
return True
return self.isMirror(root.left, root.right)
def isMirror(self, rootLeft, rootRight):
if not rootLeft and not rootRight: # have not branch
return True
if not rootLeft or not rootRight: # lack a branch
return False
return (rootLeft.val == rootRight.val) \
and self.isMirror(rootLeft.left, rootRight.right) \
and self.isMirror(rootLeft.right, rootRight.left) # trickier: acooding to symmetric tree
| true |
5281b017aa2d08bb9a22c875570a44ec76c4a540 | LXSkyhawk/cp2015 | /practical1/q7_generate_payroll.py | 1,775 | 4.125 | 4 | check = False
while check == False:
name = input("Enter name: ")
if name == "":
print("Enter your name!")
else:
check = True
check = False
while check == False:
hours = input("Enter number of hours worked weekly: ")
if any(c == "." for c in hours) == True and any(c.isdigit() for c in hours) == True:
print("Integers only!")
elif any(c.isdigit() for c in hours) == True:
hours = float(hours)
check = True
else:
print("Integers only!")
check = False
while check == False:
pay_rate = input("Enter hourly pay rate: ")
if any(c == "." for c in pay_rate) == True and any(c.isdigit() for c in pay_rate) == True:
pay_rate = float(pay_rate)
check = True
elif any(c.isdigit() for c in pay_rate) == True: # to prevent a single "." entered from ruining the code
pay_rate = float(pay_rate)
check = True
else:
print("Numbers only!")
check = False
while check == False:
cpf_rate = input("Enter CPF contribution rate(%): ")
if any(c == "." for c in cpf_rate) == True and any(c.isdigit() for c in cpf_rate) == True:
cpf_rate = float(cpf_rate)
check = True
elif any(c.isdigit() for c in cpf_rate) == True:
cpf_rate = float(cpf_rate)
check = True
else:
print("Integers only!")
gross_pay = round(hours * pay_rate, 2)
cpf_contribution = round(gross_pay * (cpf_rate/100), 2)
net_pay = round(gross_pay - cpf_contribution, 2)
print("Payroll statement for %s" % name)
print("Number of hours worked weekly: %s" % hours)
print("Hourly pay rate: $%s" % pay_rate)
print("Gross pay: $%s" % (gross_pay))
print("CPF contribution at %s percent: $%s" % (cpf_rate, cpf_contribution))
print("Net pay: $%s" % net_pay)
| true |
2d427e0fc4b45ab4be434d6d5c0b4278c9468ffb | omarmohamud23/Lab-2--Python-Basics | /student_dataclass.py | 312 | 4.15625 | 4 | from dataclasses import dataclass
@dataclass
# creating class student
class Student:
name:str
college_id: int
GPA: float
def main():
#students added with name/id and gpa
Omar = Student('Omar', 67895, 3.5)
Abdi = Student('Abdi', 76906, 2.0)
print(Omar)
print(Abdi)
main() | true |
a2a60881a07fc6f983c9da790535a2c1003ec687 | manugenerale/lmg_utils | /date/simplecalendar.py | 874 | 4.3125 | 4 | days_in_month_dict = {"January": 31, "February": 28,
"March": 31, "April": 30,
"May": 31, "June": 30,
"July": 31, "August": 31,
"September": 30, "October": 31,
"November": 30, "December": 31}
def is_leap_year(year):
'''
Return if year is lip or not
'''
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
def days_in_month(year, month):
'''
Return number of days in a given month
print(simplecalendar.days_in_month(2017, 'February'))
return 28
'''
if is_leap_year(year) and month == "February":
return 28
try:
#attempt to get value from dictionary
return days_in_month_dict[month]
except KeyError:
#key does not exist, so we caught the error
return None
| true |
d728fc6cf5e988888558ac10ff2ea8e30c3d8183 | axelqc/Problem-solving | /Ex 4.py | 609 | 4.34375 | 4 | print('''
Create a program that asks the user for a number and then prints out a list of all the
divisors of that number. (If you don’t know what a divisor is, it is a number that divides
evenly into another number.
For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
''')
x = int(input("Please intruduce a number: "))
print(f'The divisors of {x} are: ')
for elem in range(x):
if elem != 0:
y = x % elem
if y == 0:
print(elem)
print('''
source: https://www.practicepython.org/exercise/2014/02/26/04-divisors.html
''') | true |
dacef9bfc8f22e3c5c75c3773df22a6ff118abcd | RafflesG/Small-Calculator-project-kinda-garbage- | /Calculator.py | 442 | 4.21875 | 4 | print("You will be adding or subtracting 2 numbers together!")
number_1 = (input("Select a number:"))
number_2 = (input("Select another number:"))
answer = int(number_1) + int(number_2)
print(f"Your answer is {answer}!")
print("you will be multiplying 2 numbers together!")
number_1 = (input("Select a number:"))
number_2 = (input("Select another number:"))
answer = int(number_1) * int(number_2)
print(f"Your answer is {answer}!") | true |
92cd3e0adb0cfdf6e285c63189e2b66a955aefd8 | AliceHincu/FP-Assignment12 | /Parentheses.py | 1,029 | 4.1875 | 4 | from iterative import Iterative
from recursive import Recursive
if __name__ == '__main__':
print("Choose option:\n\t1.Recursive\n\t2.Iterative\n\t3.Exit")
unicorns_exist = True
while unicorns_exist:
try:
cmd = input("\n>option: ")
if cmd == "1" or cmd == "2":
n = input("n= ")
if n.isdigit():
n = int(n)
if n % 2 == 0:
if cmd == "1":
Recursive().generate_parentheses(n)
else:
Iterative().generate_parentheses(n)
else:
raise ValueError("n can't be odd")
else:
raise ValueError("Please insert a number")
else:
if cmd == "3":
unicorns_exist = False
else:
raise ValueError("Wrong command!")
except ValueError as err:
print(err)
| false |
ebd8841c53d3d00a48fa93fcf6195145225322eb | Fortune-Adekogbe/Python-Intermediate-30daysofcode.xyz | /day 19/day 19.py | 1,208 | 4.15625 | 4 | def insertion(l):
"""
An algorithm to implement the insertion sort algorithm
:param l: An array
:type l: list
:return: A sorted array
:rtype: list
"""
assert type(l)==list
for i,j in enumerate(l):
for m,n in enumerate(l):
if j<n:
l.remove(j)
l.insert(m,j)
break
if m==i:
break
return l
print(insertion(['a','c','A','e','g','K']))
def biggie(l,n):
"""
A function that returns the closest larger digit to the digit at the index n in the list l.
:param l: The list to be considered
:type l: list
:param n: The index to be considered
:type n: int
:return: The closest largest digit
:rtype: int
"""
assert type(l)==list and type(n)==int,"Wrong input type"
assert 0<n<len(l),f"{n} is out of range"
mapper = {b:a for a,b in enumerate(l)}
r,nr=-1,len(l)
for i in l[:n][::-1]:
if l[n]<i:
r=mapper[i]
break
for j in l[n+1:]:
if l[n]<j:
nr= mapper[j]
break
assert r!=-1 or nr!=len(l)
return nr if (n-r)>=(nr-n) else r
print(biggie([17,5,3,10,3,16],5)) | false |
960038072d6c3f2c4d74c5444ced7b37dc817bdf | ryanarbow/lessonprojects | /FizzBuzz.py | 482 | 4.3125 | 4 | ### Can you write a FizzBuzz algorithm? It goes like this:
### Loop through all the integers from 1 to 100
### If the number is divisible by 3, print "Fizz"
### If the number is divisible by 5, print "Buzz"
### If the number is divisible by both, print "FizzBuzz"
### If the number is divisible by neither, print the number
for i in range(1,100):
if i % 15 == 0:
print ("Fizz")
elif i % 5 == 0:
print ("Buzz")
elif i % 3 == 0:
print ("FizzBuzz")
else:
print (i)
| true |
6be29774386f97b18e3e819f359475cf7a6a4966 | deepak-karkala/algorithms_datastructures_in_python | /linked_list/singlyLinkedList.py | 1,781 | 4.15625 | 4 | """
Singly linked list
"""
class Node:
"""
Individual nodes in linked list
"""
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class SinglyLinkedList:
"""
Singly linked list class
"""
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(data=nodes.pop(0))
self.head = node
for elem in nodes:
node.next = Node(data=elem)
node = node.next
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append("None")
return " -> ".join(nodes)
def __iter__(self):
"""
Iterator to traverse a linked list
:return: individual node
"""
node = self.head
while node is not None:
yield node
node = node.next
def add_first(self, node):
"""
Add node to beginning of list
:param node: Node object
:return:
"""
node.next = self.head
self.head = node
def add_last(self, node):
"""
Add node at the end
:param node: Node object
:return:
"""
if not self.head:
self.head = node
return
n = self.head
for current_node in self:
pass
current_node.next = node
if __name__ == "__main__":
sllist = SinglyLinkedList(["a", "b", "c", "d", "e"])
print(sllist)
for n in sllist:
print(n)
sllist.add_first(Node("z"))
print(sllist)
sllist.add_last(Node("f"))
print(sllist)
| true |
d1384f7e13de907f0b5777e326d45d3d7e6bc1d6 | ram-jay07/Code-Overflow | /Powe_of_a_number | 279 | 4.5 | 4 | number = int(input(" Please Enter any Positive Integer : "))
exponent = int(input(" Please Enter Exponent Value : "))
power = 1
i = 1
while(i <= exponent):
power = power * number
i = i + 1
print("The Result of {0} Power {1} = {2}".format(number, exponent, power))
| true |
9ad721c30e81ab033d85c2701251decd34ff2b9d | hazardg/CP1404-Practicals-GeraldoGenesius | /Practical 8/trees.py | 2,533 | 4.25 | 4 | import random
TREE_LEAVES_PER_ROW = 3
class Tree:
def __init__(self):
self._trunkHeight = 1
self._leaves = TREE_LEAVES_PER_ROW
def __str__(self):
""" return a string representation of the full Tree, e.g.
###
###
|
| """
return self.getASCIILeaves() + self.getASCIITrunk()
def getASCIILeaves(self):
""" return a string representation of the tree's leaves """
result = ""
if self._leaves % TREE_LEAVES_PER_ROW > 0:
result += "#" * (self._leaves % TREE_LEAVES_PER_ROW)
result += "\n"
for i in range(self._leaves // TREE_LEAVES_PER_ROW):
result += "#" * TREE_LEAVES_PER_ROW
result += "\n"
return result
def getASCIITrunk(self):
""" return a string representation of the tree's trunk """
result = ""
for i in range(self._trunkHeight):
result += " | \n"
return result
def grow(self, sunlight, water):
""" take in an amount sunlight and water
randomly grow the trunkHeight by a number between 0 and water
randomly increase the leaves by a number between 0 and sunlight """
self._trunkHeight += random.randint(0, water)
self._leaves += random.randint(0, sunlight)
class EvenTree(Tree):
""" represent an even tree, one that only grows leaves in full rows """
def grow(self, sunlight, water):
""" takes in an amount of sunlight and water
grow like a normal tree, but fill out each row of leaves """
Tree.grow(self, sunlight, water)
while self._leaves % 3 != 0:
self._leaves += 1
class UpsideDownTree(Tree):
""" represent an upside-down tree; just like a normal tree, but appears upside-down """
def __str__(self):
""" return a string representation of the full tree, upside-down compared to a normal tree """
return self.getASCIITrunk() + self.getASCIILeaves()
class WideTree(Tree):
""" wide tree: grows twice as wide as a normal tree, e.g.
#####
######
######
||
|| """
pass
class QuickTree(Tree):
""" tree that grows more quickly """
pass
class FruitTree(Tree):
""" tree that has fruit as well as leaves, e.g.
.
...
##
###
###
|
| """
pass
class PineTree(Tree):
""" pine tree, e.g.
*
***
*****
*******
|
| """
pass
| false |
9e781e1c2d0a308b236e150a77d6d10fb0f5b7c7 | manoj543/Data-structures-problem-solving | /Bit manipulation/ReverseBits.py | 647 | 4.25 | 4 | """
Problem Description
Reverse the bits of an 32 bit unsigned integer A.
Problem Constraints
0 <= A <= 232
Input Format
First and only argument of input contains an integer A.
Output Format
Return a single unsigned integer denoting the decimal value of reversed bits.
Example Input
Input 1:
0
Input 2:
3
Example Output
Output 1:
0
Output 2:
3221225472
"""
# @param A : unsigned integer
# @return an unsigned integer
def reverse(A):
b1 = bin(A).replace('0b', '')
b1 = b1.zfill(32) # Zero filling
b2 = ''
total_bits = len(b1)
j = total_bits - 1
while(j>=0):
b2 += b1[j]
j -= 1
return int(b2,2)
| true |
dc13ebba516ac55c7f0bafee73eba3a8a004414b | Lenee/Beginner-Python | /Miles_per_gallon.py | 236 | 4.3125 | 4 | #This program is to calculate miles per gallon
miles=float(input('Please enter the miles traveled: '))
gallons=float(input('Please enter how many gallons of gas used: '))
mpg=miles/gallons
print('Your MPG is: ', format(mpg,'.2f'),'!')
| true |
a96b9ba451a35520a2a3a81f552955bb9f5a488d | anoopsingh/PerlPractice | /PythonLearning/Class/class_basic.py | 320 | 4.25 | 4 | class User:
name = ""
def __init__(self,name):
self.name = name
def sayHello(self):
print "Hello, my name is " + self.name
# create virtual objects
James = User("James");
david = User("david");
eric = User("eric");
## Call methods own by virtual objects
James.sayHello()
david.sayHello()
| false |
5669be4a04b385057a8affe7f75855b3aab32470 | electroNBS/LineGraphPlot | /ScatterPlot.py | 1,100 | 4.3125 | 4 | # Plotting a line graph about cases over time in different countries
# Importing the pandas module in python using alias "pd" so that we don't have to write "pandas"
# every time we want to use the pandas module
import pandas as pd
# Importing the express submodule from plotly module in python using alias "pd" so that we don't
# have to write "pandas" every time we want to use the pandas module
import plotly.express as px
# pandas module helps to read data from tables(csv files) and store it as a dataframe(a kind of datatype)
# Reading a csv file and storing its values in a data variable.
data = pd.read_csv("data.csv")
# px has a predefined function called line that helps to plot a line graph
# We assign the data variable that contains the values to be plotted as an argument.
# Assigning the independent and dependent values from the csv file to the x and y axes respectively.
# Assigning another property color to the country values so that each country in the graph has a
# different color.
figure = px.line(data, x="date", y="cases", color="country")
# Showing the graph
figure.show()
| true |
d39061950f74b9a9329e198340e44319b1ac1224 | hsanson/logo-playground | /solution03.py | 1,030 | 4.34375 | 4 | """
Solution 03
Objective:
- Practice with adquired knowledge to implement different shapes.
- Observe patterns in the implementations.
Documentation:
- https://docs.python.org/3.7/library/turtle.html
"""
import turtle
jim = turtle.Turtle()
canvas = jim.getscreen()
def start():
reset()
draw_square(100)
draw_triangle(100)
draw_pentagon(100)
draw_star(100)
def draw_square(size):
for _ in range(0, 4):
jim.forward(size)
jim.left(90)
def draw_triangle(size):
for _ in range(0, 3):
jim.forward(size)
jim.left(120)
def draw_pentagon(size):
for _ in range(0, 5):
jim.forward(size)
jim.left(72)
def draw_star(size):
for _ in range(0, 9):
jim.forward(size)
jim.left(225)
def reset():
jim.reset()
jim.color('blue')
jim.pensize(5)
jim.shape('turtle')
def mainloop():
canvas.listen()
canvas.onkey(start, "r")
canvas.mainloop()
if __name__ == "__main__":
reset()
mainloop()
| false |
1b3f0cd7a5efbd30de1b37e3736200d702644125 | rudolphlogin/Python_training | /iterations/list_zip.py | 1,475 | 4.125 | 4 | ''' List comprehensions and the zip function '''
from random import randint
from pprint import PrettyPrinter
keys = range(1,5)
values = range(10,41,10)
print('keys:',[key for key in keys])
print('values:',[value for value in values])
tuple_list = zip(keys,values)
print('List of tuples:',[pair for pair in tuple_list])
zip_keys,zip_values = zip(*zip(keys,values)) #unzip
print('Keys from zip:',[key for key in zip_keys])
print('values from zip:',[value for value in zip_values])
dict_zip = dict(zip(keys,values))
print('dictionary of keys and values:',dict_zip)
#matrix3x3 =[[randint(1,10) for y in range(3)] for x in range(3)]
matrix3x3 = [
[4,2,1],
[10,3,1],
[10,10,10]
]
print('3 x 3 matrix:')
pp = PrettyPrinter(indent=4, width=30)
pp.pprint(matrix3x3)
print('without pprint :',matrix3x3)
#matrix3x4 = [[randint(1,0) for y in range(4)] for x in range(3)]
matrix3x4 =[
[9,5,7,8],
[8,4,4,3],
[8,1,9,5]
]
print('3x4 matrix:')
pp.pprint(matrix3x4)
matrix_mult =[
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
for x in range(len(matrix3x3)):
for y in range(len(matrix3x4[0])):
for z in range(len(matrix3x4)):
matrix_mult[x][y] += matrix3x3[x][z] * matrix3x4[z][y]
print('Multiplication matrix:')
pp.pprint(matrix_mult)
# another method
matrix_mult= [[sum(x * y for x,y in zip(rows,cols))for cols in zip(*matrix3x4)] for rows in matrix3x3]
print('Multiplication matrix:')
pp.pprint(matrix_mult)
| true |
bd05a9f4338935ee13f00a6e5ef8e0865c7d0505 | ashleyannlaz/Learning-Python-Notes | /Ch2/2_Functions.py | 918 | 4.40625 | 4 | # Python Functions
# Define basic function
def func1():
print('I am a function')
# PRINT FUNCTIONS
# func1()
# print(func1())
# # functions are objects
# print(func1)
# --------------------------------
# Function that takes arguments
def func2(arg1, arg2):
print(arg1, "", arg2)
# func2(10,20)
# print(func2(10,20))
# --------------------------------
# Function that returns a value
def cube(x):
return x*x*x
# cube(3)
# print(cube(3))
# --------------------------------
# Function with default value for an argument
def power(num, x = 1):
result = 1
for i in range(x):
result = result * num
return result
# print(power(2))
# print(power(2,3))
# You can input args in the opposite
# print(power(x=3, num=2))
# function with variable number or args
def multi_add(*args):
result = 0
for x in args:
result = result + x
return result
print(multi_add(1,1,2))
| true |
58017dd7ae83a88f32f3242c975fde2fde8cf940 | kevinhynes/data-structures-capstone | /script.py | 2,583 | 4.125 | 4 | from trie import Trie
from data_structures import *
from data import cuisines, restaurant_data
import welcome
from collections import namedtuple
def build_trie(word_list):
for cuisine in cuisines:
t.insert(cuisine)
def test_trie(word_list):
for item in word_list:
search_string = item[0][0] # first letter of cuisine type
search_results = t.search(search_string)
print("Searching for '{}': \t Found: {}"
.format(search_string, search_results))
def build_ll(word_list):
new_linked_list = CuisineList()
for word in word_list:
new_linked_list.insert_beginning(word)
return new_linked_list
def print_restaurant_names(restaurant_list):
for r in restaurant_list:
print(r[1])
Restaurant = namedtuple("Restaurant_nt",
['cuisine', 'name', 'price', 'rating', 'address'])
def build_data_structure(cuisine_list, restaurant_list):
cuisine_ll = build_ll(cuisine_list)
# TODO create build_hashmaps function
for r in restaurant_list:
new_restaurant = Restaurant(*r)
cuisine_node = cuisine_ll.search(new_restaurant.cuisine)
cuisine_node.value.assign(new_restaurant.name, new_restaurant)
return cuisine_ll
def list_by_cuisine(cuisine_type, data_structure):
cuisine_node = data_structure.search(cuisine_type)
print(cuisine_node.value.stringify_array())
t = Trie()
build_trie(cuisines)
data_structure = build_data_structure(cuisines, restaurant_data)
welcome.print_welcome()
opening_message = "\nWhat type of food would you like to eat?" \
"\nType the beginning of that food type and press enter" \
"to see if it's here.\n"
while True:
user_input = input(opening_message)
search_results = t.search(user_input)
if search_results is None:
print("\nSorry, we don't have that cuisine available!")
elif len(search_results) > 1:
print("\nYour search returned these results: {}".format(search_results))
elif len(search_results) == 1:
match = search_results[0]
print(f"\nThe only cuisine with those beginnging letters is {match.capitalize()}")
user_input = input(f"\nWould you like to see {match.capitalize()} restaurants? Enter 'y' for yes"
" and 'n' for no.")
if user_input == 'y':
list_by_cuisine(match, data_structure)
elif user_input == 'n':
print(f"\nThank you, Good bye!")
break
else:
print(f"\nThat is not a valid choice.")
| true |
1e062f354d6235610e75c7847a65304ebc6640a4 | DaPenguinNinja/Testing-Python | /ReadWrite.py | 1,030 | 4.125 | 4 | #Open a file to read
employee_file= open("employee.txt","r")
#Read from file
#print(employee_file.read())
#read 2 single lines from file
print(employee_file.readline())
print(employee_file.readline())
#for loop to read remaining lines of code
for employee in employee_file.readlines():
print(employee)
#close file so its no longer affected
employee_file.close()
#open file to add lines to it with "a"
employee_file = open("employee.txt","a")
#Write line to end of file onto next line with '\n'
employee_file.write("\nToby - Human Resources")
#add new line
employee_file.write("\n")
#add another line to file
employee_file.write("Kelly - Customer Service")
#close file
employee_file.close()
#Adding "w" to a file will create a file or overwrite a file of the same name
employee_file = open("employee1.txt","w")
employee_file.write("Kevin-Accountant")
employee_file.close()
#Can even create HTML page
employee_file = open("index.html","w")
employee_file.write("<h>Penguins are Awesome webpage</h>")
employee_file.close()
| true |
59c7a95f41616ea14d590a877b7c6a94eb3bad03 | khatria/Data-Structures-in-Python | /Arrays/getOddOccurenceNumber.py | 926 | 4.34375 | 4 | """
find the number occuring odd number of times in an array, given that exactly
one number occurs odd number of times
"""
def getOddOccurence1(lst):
'''
Using hash table
'''
count_dict = {}
for ele in lst:
if count_dict.get(ele) == None:
count_dict[ele] = 1
else:
count_dict[ele] += 1
return max(count_dict, key=count_dict.get)
print('The element occuring odd number of times is {}'.format(getOddOccurence1([3, 2, 1, 2, 3, 1, 1])))
def getOddOccurence2(lst):
'''
Using xor: If a number occurs even number of times and we apply XOR on it, we get result as zero and
odd number of times then we get the number itself
'''
result = 0
for element in lst:
result = result ^ element
return result
print('The element occuring odd number of times is {}'.format(getOddOccurence2([3, 2, 1, 2, 3, 1, 1]))) | true |
572ba89de1d38287a46de1de41b5615ab0f2bb65 | khatria/Data-Structures-in-Python | /Stack/string_reverse.py | 380 | 4.28125 | 4 | """
Given a string, this code generates the reverse of the string
"""
from stack import Stack
def reverse_string(s):
my_stack = Stack()
[my_stack.push(s[i]) for i in range(len(s))]
reverse_string = ''
while not my_stack.is_empty():
reverse_string += my_stack.pop()
return reverse_string
print(reverse_string('irtahk kehsihba')) | true |
40e07862c5583e08f5eb8eb48ef13ad43f0b9e1a | rudrut/data_analytics-python-exercises-2020 | /rudi_rutanen-python_harjoitus-1.py | 575 | 4.15625 | 4 | import random as rand
import numpy as np
# a)
entries = int(input("How many random numbers? "))
# b)
randomMin = int(input("Determine minimum: "))
randomMax = int(input("Determine maximum: "))
amountOfRandoms = np.full(entries, 0)
# c)
for i in range(0, amountOfRandoms.size):
amountOfRandoms[i] = rand.randrange(randomMin, randomMax)
sorted_array = np.sort(amountOfRandoms)
reverse_array = sorted_array[::-1]
# d)
print("Numbers in ascending order: " + str(sorted_array))
# e)
print("Numbers in descending order: " + str(reverse_array)) | true |
dbda4a7f20e23899fe081f7b260e06aafe9a72e7 | rvsmegaraj1996/Megaraj | /pyramid.py | 404 | 4.125 | 4 | #pyramid
'''
n=8
limit=1
for row in range(1,n+1):
for space in range(n-1,row-1,-1): print(" ",end="")
for data in range(1,limit+1): print("*",end="")
limit+=2;print()
'''
n=int(input("tell us how many rows you wish:"))
limit=1
for row in range(n,0,n+1):
for space in range(n-1,row-1,-1):print(" ",end="")
for data in range(1,limit+1):print("*",end="")
limit+=2;print()
| false |
cae750e0f9c26a10830867e018ac05c0f02b2269 | Uttam1982/PythonTutorial | /14-Python-Advance/02-python-Generators/03-Create-Generators.py | 1,260 | 4.34375 | 4 | # yield statement pauses the function saving all its states and later continues
# from there on successive calls.
#-------------------------------------------------------------------------------------
# A simple generator function
def my_gen():
for i in range(3):
print(f"Before yield: {i}")
yield i
print(f"After yield: {i}")
gen = my_gen()
print(next(gen))
# Once the function yields, the function is paused and the control is transferred to the caller.
# Local variables and theirs states are remembered between successive calls.
print(next(gen))
print(next(gen))
# Finally, when the function terminates, StopIteration is raised automatically on further calls
# print(next(gen))
#-------------------------------------------------------------------------------------
# Using for loop
print("-------------------------")
print("Using For Loop\n")
for i in my_gen():
print(i)
#-------------------------------------------------------------------------------------
iter_obj = my_gen()
print("-------------------------")
print("Using while Loop\n")
while True:
try:
element = next(iter_obj)
print(element)
except StopIteration:
break
#------------------------------------------------------------------------------------- | true |
188900077df0d78d38fe592b81a14eed22d29f56 | Uttam1982/PythonTutorial | /03-Python-Function/09-function-default-arguments.py | 1,408 | 4.84375 | 5 | # Types of arguments
# There may be several types of arguments which can be passed at the time of function call.
# 1. Required arguments
# 2. Default arguments
# 3. Keyword arguments
# 4. Variable-length arguments
#********************************************************************************************
# Default arguments
#********************************************************************************************
# Function arguments can have default values in Python.
# We can provide a default value to an argument by using the assignment operator (=).
def add(x,y=2):
return x+y
sum= add(1)
print("sum = ",sum)
sum= add(1,5)
print("sum = ",sum)
# TypeError: add() missing 1 required positional argument: 'x'
# sum = add()
# print("sum = ",sum)
#Explanation
# 1. In this function, the parameter x does not have a default value
# and is required (mandatory) during a call.
# 2. The parameter y has a default value of 2. So, it is optional during a call.
# If a value is provided, it will overwrite the default value.
# 3. Any number of arguments in a function can have a default value.
# But once we have a default argument, all the arguments to its right must also have
# default values
# 4. This means to say, non-default arguments cannot follow default arguments.
# def add(x = 2,y):
# return x+y
# SyntaxError: non-default argument follows default argument | true |
939933aecef4b2809732f76a7d649a0a637214e6 | Uttam1982/PythonTutorial | /01-Python-Introduction/04-Python Variables/01-python-variables.py | 594 | 4.5 | 4 | # Python Variables
number = 10
# Here, we have created a variable named number. We have assigned the value 10 to the variable.
number = 1.1
# initially, the value of number was 10. Later, it was changed to 1.1
# Example 1: Declaring and assigning value to a variable
person = "Sam"
print(person)
# Example 2: Changing the value of a variable
person ='Joe'
print(person)
# Example 3: Assigning multiple values to multiple variables
a, b, c = 10, 4.5, 'Sam'
print(a)
print(b)
print(c)
# Example 4: Assigning the same value to multiple variables
x = y = z = 10
print(x)
print(y)
print(z)
| true |
72e81651d24fc31bca49025a88ee2cd347202140 | Uttam1982/PythonTutorial | /09-Python-FileIO/01-Python-File-Operations/09-writing-to-file-with-mode-a.py | 1,035 | 4.21875 | 4 | #**************************************************************************************
# Writing to Files in Python
#**************************************************************************************
# In order to write into a file in Python, we need to open it different mode
# 1. in write: w,
# 2. append: a
# 3. exclusive creation: x
# We need to be careful with the w mode, as it will overwrite
# into the file if it already exists. Due to this, all the
# previous data are erased.
# Writing a string or sequence of bytes (for binary files) is done using the write() method.
# This method returns the number of characters written to the file.
#**************************************************************************************
try:
# open the file1.txt in append mode.
f = open('file1.txt','a',encoding='utf-8')
print('file opened successfully in append mode')
# appending the content to the file
f.write("This is the fourth line\n")
finally:
print('file closed successfully!')
f.close()
| true |
b7b1c2348eca9ed69abc9d1b5368b4ee86ed1132 | Uttam1982/PythonTutorial | /01-Python-Introduction/05-Python-Data-Types/04-data-type-list.py | 875 | 4.375 | 4 | # Python List
# - List is an ordered sequence of items.
# - It is very flexible.
# - Lists are mutable, meaning, the value of elements of a list can be altered.
# - All the items in a list do not need to be of the same type.
# Declaring a list
# Items separated by commas are enclosed within brackets [ ].
alist = [1,2.2,'python']
print(alist)
# Use the slicing operator [ ] to extract an item or a range of items from a list.
# The index starts from 0 in Python.
a = [10,20,30,40,50,60,70,80,90]
#Extract the 3rd element in the list
print("a[2] = ",a[2])
#Extract the first three element
print("a[0:3] = ",a[0:3] )
print("a[:3] = ",a[:3] )
#Extract the last element
print("a[8] = ",a[8])
print("a[-1] = ",a[-1])
#Extract the last three elements
print("a[6:10] = ",a[6:10] )
print("a[6:] = ",a[6:] )
print("a[-3:] = ",a[-3:] )
# Lists are mutable
a[2]= 31
print(a) | true |
03c18ea197235c77730ceff34b9568144285ae24 | Uttam1982/PythonTutorial | /08-Python-DataTypes/Tuples/10-tuple-membership-test.py | 355 | 4.21875 | 4 | # 1. Tuple Membership Test
# We can test if an item exists in a tuple or not, using the keyword in.
my_tuple = (12,23,34,45,56,67,78,89,90)
# In operation
print("23 in my_tuple: ",23 in my_tuple) #True
# not in operation
print("23 not in my_tuple: ",23 not in my_tuple) #False
# not in operation
print("43 not in my_tuple: ",43 not in my_tuple) #True | true |
41b751f1c78e9164827af24d386b15c7b0c8d6fb | Uttam1982/PythonTutorial | /05-Build-in-function/06-python-bool.py | 1,149 | 4.375 | 4 | # Python bool()
# The bool() method converts a value to Boolean(True or False) using standard truth
# testing procedure
# It's not mandatory to pass a value to bool().
# If you don't pass a value, bool() returns False.
# The following values are consider false in python:
# 1. None
# 2. False
# 3. Zero of any numeric type. Example, 0, 0.0, 0j
# 4. Empty sequence. For example '', [], ()
# 5. Empty mapping. For example, {}
# 6. objects of classes which implement __bool()__ or __len()__ which return 0 or False
# All other values except these values are considered true.
# *****************************************************************************************
# Example: How bool() works?
print("No parameter pass to bool() method: ",bool())
test = None
print(test, ' is ', bool(test))
test = False
print(test, ' is ', bool(test))
test = []
print(test, ' is ', bool(test))
test = ()
print(test, ' is ', bool(test))
test = ''
print("''", ' is ', bool(test))
test = 0
print(test, ' is ', bool(test))
test = 0.0
print(test, ' is ', bool(test))
test = 0j
print(test, ' is ', bool(test))
test = 'python'
print(test, ' is ', bool(test))
| true |
52fe7ccdea8a83ad99880d8f7f4c3e2901fa5154 | Uttam1982/PythonTutorial | /14-Python-Advance/06-python-regex/04-Match-Object/01-Match-Methods/01-Match-Object.py | 660 | 4.15625 | 4 | # Match Object Methods and Attributes
#--------------------------------------------------------------------------------------------
# As you’ve seen, most functions and methods in the re module return a match object
# when there’s a successful match. Because a match object is truthy, you can use it
# in a conditional:
import re
m = re.search('bar','foo.bar.baz')
# Output : <re.Match object; span=(4, 7), match='bar'>
print(m)
# Output : True
print(bool(m))
if re.search('bar','foo.bar.baz'):
print('Found a match')
else:
print('No match found')
#--------------------------------------------------------------------------------------------
| true |
0978e0efcae6a62b911e930a25901af3dc4cd36f | Uttam1982/PythonTutorial | /08-Python-DataTypes/Lists/11-remove-method-list.py | 370 | 4.125 | 4 | # We can use remove() method to remove the given item
# The remove() method removes the first matching element
my_list = [12,45,34,45,56,67,45,89,90]
print(my_list)
#in remove we pass the element value not the index
my_list.remove(45)
print(my_list)
my_list.remove(45)
print(my_list)
# if the element doesn't exist : ValueError
my_list.remove(65)
print(my_list)
| true |
83d21f29c24ea22b568c8f110f60e951737b6caa | Uttam1982/PythonTutorial | /14-Python-Advance/03-Python-Generator-Expression/01-generator-expression.py | 1,747 | 4.5 | 4 | #--------------------------------------------------------------------------------------------
# Python Generator Expression
#--------------------------------------------------------------------------------------------
# Similar to the lambda functions which create anonymous functions,
# generator expressions create anonymous generator functions.
# The syntax for generator expression is similar to that of a list comprehension in Python.
# But the square brackets are replaced with round parentheses.
# The major difference between a list comprehension and a generator expression is that
# a list comprehension produces the entire list while
# the generator expression produces one item at a time.
# They have lazy execution ( producing items only when asked for ).
# For this reason, a generator expression is much more memory efficient
# than an equivalent list comprehension.
#--------------------------------------------------------------------------------------------
# initialize a list
lst = [2,3,4,5]
# square each item using list comprehension
squares = [x * x for x in lst ]
# Output : [4, 9, 16, 25]
print(squares)
# same thing can be done using a generator expression
# generator expressions are surrounded by parenthesis ()
squares_gen = (x * x for x in lst)
# Output: <generator object <genexpr> at 0x7ff747c485d0>
print(squares_gen)
# We can see above that the generator expression did not produce the required result immediately.
# Instead, it returned a generator object, which produces items only on demand.
# Output: 4
print(next(squares_gen))
# Output: 9
print(next(squares_gen))
# Output: 16
print(next(squares_gen))
# Output: 25
print(next(squares_gen))
# output : StopIteration
print(next(squares_gen))
| true |
212a75e8ccb4c006309a66ff138876fa7d5c02e9 | Uttam1982/PythonTutorial | /11-Python-Object-Oriented-Programming/06-revise-oops-concepts.py/10_class_and_static_method.py | 900 | 4.46875 | 4 | # python program to demonstrate
# use of class method and static method
from datetime import date
class Person:
#instance attribute
def __init__(self, name,age):
self.name = name
self.age = age
# A class method to create Person object by birth year
@classmethod
def fromBithYear(cls,name, year):
return cls(name, date.today().year - year)
# static method to check the person is adult or not
@staticmethod
def isAdult(age):
if age > 18:
print("You are adult")
else:
print("You are not adult")
#instance method
def display_age(self):
print(f"{self.name} your age is: {self.age}")
#instantiating a class
person1 = Person('Sam',16)
#calling class method to create object
person2 = Person.fromBithYear('Ben',1990)
person1.display_age()
person2.display_age()
# calling static method
Person.isAdult(person1.age)
Person.isAdult(person2.age)
| true |
008d492ea0d5139c0bda2a7713e8b4b5684dd80d | Uttam1982/PythonTutorial | /14-Python-Advance/06-python-regex/01-MetaCharacters/11-group-symbol.py | 651 | 4.5 | 4 | #---------------------------------------------------------------------------------------
# () - Group
#---------------------------------------------------------------------------------------
# Parentheses () is used to group sub-patterns.
# For example, (a|b|c)xz match any string that matches either a or b or c followed by xz
#---------------------------------------------------------------------------------------
import re
pattern ="(a|b|c)xz"
mylist = ['ab xz','abxz','axz' ,'cabxz']
result = [x for x in mylist if re.search(pattern,x)]
print(result)
#--------------------------------------------------------------------------------------- | true |
bf3966738a5a74e6a9366e20f646de006b9c907a | Uttam1982/PythonTutorial | /08-Python-DataTypes/Lists/06-append-method-list.py | 562 | 4.71875 | 5 | # append() method
# The append() method adds an item to the end of the list.
# We can add one item to a list using the append() method
# Appending and Extending lists in Python
# Example 1: Add one element on the list
my_list = [2,4,6,8]
my_list.append(1)
print(my_list) # [2, 4, 6, 8, 1]
# Example 2: Adding List to a List
my_list.append([1,3,5,7])
print(my_list) # [2, 4, 6, 8, 1, [1, 3, 5, 7]]
# If you need to add items of a list to another list
# (rather than the list itself), use the extend() method.
| true |
fc7fb4e649fcd40b2bb683d4c808e2824d63463d | Uttam1982/PythonTutorial | /08-Python-DataTypes/Dictionary/02-create-dictionary.py | 1,362 | 4.75 | 5 | # Creating Python Dictionary
# 1. Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
# 2. An item has a key and a corresponding value that is expressed as a pair (key: value).
# 3. While the values can be of any data type and can repeat,
# 4. keys must be of immutable type (string, number or tuple with immutable elements) and
#
# 5. Keys must be unique.
#1. Create an empty dictionary
my_dict = {}
print("empty dictionary: ",my_dict)
print('type of empty dictionary: ', type(my_dict))
#2. Create dictionary with integer keys
my_dict = {1:'Sam',2:'Joe',3:'Ben'}
print("dictionary with integer keys: ",my_dict)
#3. Create dictionary with mixed keys
my_dict = {1:'Sam','marks':[90,98,89]}
print("dictionary with mixed keys: ",my_dict)
# 4. using dict() function
my_dict = dict({1:'Sam',2:'Joe',3:'Ben'})
print("using dict() function integer keys: ",my_dict)
# from sequence having each item as a pair
my_dict = dict([('name','Sam'),('age',21),('balc',1234.567)])
print("using dict() from sequence having each item as a pair: ",my_dict)
# Formatting dictionary members using format()
print("Name = {m[name]} Age = {m[age]} and Balance = {m[balc]}".format(m=my_dict))
# Format dictionaries in Python using str.format(**mapping).
print("Name = {name}, Age = {age} and Balance = {balc}".format(**my_dict)) | true |
51ffb68e66d6b003762a720ad5ea0dfd5a3e3149 | Uttam1982/PythonTutorial | /08-Python-DataTypes/Lists/List-Methods/08-copy-method.py | 1,272 | 4.84375 | 5 | #The copy() method returns a shallow copy of the list.
# A list can be copied using the = operator.
my_list = [1,2,3,4]
c_list = my_list
print('my_list: ',my_list)
print('copy_list: ',c_list)
# The problem with copying lists in this way is that if you modify c_list,
# my_list is also modified.
c_list.append(5)
print('modified my_list: ',my_list)
print('modified copy_list: ',c_list)
# However, if you need the original list unchanged when the new list is modified,
# you can use the copy() method.
#*************************************************************************************************
## shallow copy using the copy method
my_list = [1,2,3,4]
#The copy() method returns a new list. It doesn't modify the original list.
c_list = my_list.copy()
c_list.append(5)
print('modified my_list: ',my_list)
print('modified copy_list: ',c_list)
#*************************************************************************************************
#Example : Copy List Using Slicing Syntax
my_list = [1,2,3,4]
# shallow copy using the slicing syntax
c_list = my_list[:]
c_list.append(5)
print('modified my_list: ',my_list)
print('modified copy_list: ',c_list)
#*************************************************************************************************
| true |
0c14de28047bd5d7b3124fa0088627a2782656e6 | Uttam1982/PythonTutorial | /14-Python-Advance/06-python-regex/01-MetaCharacters/01-what-is-RegEx.py | 1,075 | 4.71875 | 5 | # Python RegEx
#-------------------------------------------------------------------------------------------
# A Regular Expression (RegEx) is a sequence of characters that defines a search pattern.
#-------------------------------------------------------------------------------------------
# For example
# ^a...s$
# The pattern is: any five character starting with 'a' and ending with 's'
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
print(result)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
#-------------------------------------------------------------------------------------------=
# Python has a module named re to work with RegEx.
import re
pattern = '^a...s$'
test_string = ['abs','alias','abyss','Alias','abacus']
# abs - No match
# alias - Match
# abyss - Match
# Alias - No match
# An abacus -No match
result = [x for x in test_string if re.search(pattern,x)]
print(result)
#-------------------------------------------------------------------------------------------=
| true |
570b2c769189ba5ce11aa2f873cb94bc052b5a3b | Uttam1982/PythonTutorial | /02-Python-Flow-Control/03-range-function.py | 1,586 | 4.6875 | 5 | # The range() function
# **********************************************************************************
# 1. We can generate a sequence of numbers using range() function.
# 2. range(10) will generate numbers from 0 to 9 (10 numbers).
# 3. We can also define the start, stop and step size as range(start, stop,step_size).
# 4. step_size defaults to 1 if not provided.
# 5. This function does not store all the values in memory; it would be inefficient.
# So it remembers the start, stop, step size and generates the next number on the go.
# 6. To force this function to output all the items, we can use the function list().
#************************************************************************************
#Example : range() function
# This function does not store all the values in memory
# So it remembers the start, stop, step size and generates the next number on the go.
print(range(10))
# To force this function to output all the items, we can use the function list()
print(list(range(10)))
# step_size defaults to 1 if not provided.
print(list(range(2, 8)))
# step_size 2
print(list(range(2,10,2)))
# **********************************************************************************
# We can use the range() function in for loops to iterate through a sequence of numbers.
# It can be combined with the len() function to iterate through a sequence using indexing.
students = ['sam','joe','sara']
for i in range(len(students)):
print("student name= ",students[i])
#***********************************************************************************
| true |
0534aec84e9bd75e34af0dfec07f5fd179e0fc42 | Uttam1982/PythonTutorial | /02-Python-Flow-Control/01-If-else.py | 2,654 | 4.375 | 4 | # What is if...else statement in Python?
# Decision making is required when we want to execute a code only
# if a certain condition is satisfied.
# The if…elif…else statement is used in Python for decision making.
# ******************************************************************************
# Python if Statement Syntax
# ******************************************************************************
# Will execute statement(s) only if the test expression is True.
# If the test expression is False, the statement(s) is not executed.
# Example: Python if Statement
num = 5
if num > 0:
print(num, "is a postive number")
print("This will always be printed")
num = -1
if num > 0:
print(num, "is a postive number")
print("This will always be printed")
# ******************************************************************************
# Python if...else Statement
# ******************************************************************************
# If the condition is False, the body of else is executed.
# Indentation is used to separate the blocks.
# Example of if...else
#num = 5
#num = -1
num = 0
if num >= 0:
print("Positive or zero")
else:
print("Negative number")
# ******************************************************************************
# Python if...elif...else Statement
# ******************************************************************************
# The elif is short for else if. It allows us to check for multiple expressions.
# If the condition for if is False, it checks the condition of the next elif block and so on.
# If all the conditions are False, the body of else is executed.
# The if block can have only one else block. But it can have multiple elif blocks.
# Example of if...elif...else
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 5
# num = 0
# num = -1
if num > 0:
print("positive number")
elif num == 0:
print("Zero")
else:
print("Negaive number")
# ******************************************************************************
# Python Nested if statements
# ******************************************************************************
# We can have a if...elif...else statement inside another if...elif...else statement.
# This is called nesting in computer programming.
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''
num = float(input("Enter a number : "))
if num >= 0:
if num == 0:
print("zero")
else:
print("Positive number")
else:
print("Negative number")
| true |
5d576a28a6457ddbff245640798dfc7f3c48c154 | Uttam1982/PythonTutorial | /08-Python-DataTypes/Python-Iteration-Skills /04-Filter-Elements-With-filter-method.py | 1,066 | 4.6875 | 5 | #-------------------------------------------------------------------------------------------
# 4. Filter Elements With filter()
#-------------------------------------------------------------------------------------------
# You don’t always need to use all the items in the iterable.
# In these cases, we can usually check if items satisfy particular criteria before
# we apply the needed operations. Such condition evaluation and creation of the
# needed iterator can be easily integrated into one function call — filter().
# Let’s see how it works in comparison to the typical way.
#-------------------------------------------------------------------------------------------
# A list of numbers to process
numbers = [12,23,34,45,56,67,78,89,90]
#typical ways
print('typical ways')
for num in numbers:
if num%2:
print("odd number: ",num)
#typical ways
for num in numbers:
if num%2 ==0:
print("even number: ",num)
# using filter()
print('using filter() functions')
for num in filter(lambda x: x%2, numbers):
print("odd number: ",num)
| true |
c3b26859084fc1303b521777e3b26060d5f65f70 | Uttam1982/PythonTutorial | /10-Python-Exceptions/09-Creating-Custom-Exceptions.py | 1,151 | 4.375 | 4 | #---------------------------------------------------------------------------------------
# Creating Custom Exceptions
#---------------------------------------------------------------------------------------
# In Python, users can define custom exceptions by creating a new class.
# This exception class has to be derived, either directly or indirectly,
# from the built-in Exception class.
# Most of the built-in exceptions are also derived from this class.
#---------------------------------------------------------------------------------------
# define Python user-defined exceptions
class CustomError(Exception):
pass
#---------------------------------------------------------------------------------------
# we have created a user-defined exception called CustomError which inherits from
# the Exception class. This new exception, like other exceptions, can be raised
# using the raise statement with an optional error message.
try:
num = int(input("Enter a number : "))
if num < 10:
raise CustomError('The value is too small')
except CustomError as e:
print(f"Error : {e}")
else:
print(f"The {num} is greater than 10") | true |
4d62ae194ab6d9cd0f0886b5a152083be8205a15 | Uttam1982/PythonTutorial | /11-Python-Object-Oriented-Programming/03-Python-Constructor/04-create-attribute-on-fly.py | 1,101 | 4.71875 | 5 | # Create a new attribute
# attributes of an object can be created on the fly.
class Employee:
"""This is an Employee Class"""
#Parameterized constructor have two attributes id and name
def __init__(self, id, name):
self.id = id
self.name = name
def display(self):
print(f"#Id: {self.id}, Name: {self.name}")
# Create a new Employee object
emp1 = Employee("Sam", 23)
# Call display() method
# Output: #Id: Sam, Name: 23
emp1.display()
# Create another Employee object
# and create a new attribute 'attr'
emp2 = Employee("Ben", 21)
emp2.attr = 10
# Output : #Id: Ben, Name: 21, Attr: 10
print(f"#Id: {emp2.id}, Name: {emp2.name}, Attr: {emp2.attr}")
# but emp1 object doesn't have attribute 'attr'
# AttributeError: 'Employee' object has no attribute 'attr'
print(f"#Id: {emp1.id}, Name: {emp1.name}, Attr: {emp1.attr}")
# An interesting thing to note in the above step is that attributes of an object
# can be created on the fly.
# We created a new attribute attr for object emp2 and read it as well.
# But this does not create that attribute for object emp1.
| true |
117370c2464854a320f4066b330df1cdf5ae4c66 | Uttam1982/PythonTutorial | /08-Python-DataTypes/Lists/List-Methods/10-count-method.py | 416 | 4.21875 | 4 | #count() method
# The count() method returns the number of times the specified element appears in the list.
# Example 1: Use of count()
# output : 3
my_list = [10,20,30,40,20,50,20]
print(my_list.count(20))
print(my_list.index(20))
# Example 2: Count Tuple and List Elements Inside List
my_list = [1,(2,3),(2,3),[4,5]]
# Count Tuple : 2
print(my_list.count((2,3)))
# Count list : 1
print(my_list.count([4,5])) | true |
45626b49de4eee4addecffbd36ea6d9c3c2e0d28 | ahmdeen/Bioinformatic-Algorthims | /Ros1A_FreqWords.py | 1,804 | 4.28125 | 4 | """
Frequent Words
Find the most frequent k-mers in a string.
Given: A DNA string Text and an integer k.
Return: All most frequent k-mers in Text (in any order).
Algorithm:
* Iterate through intervals of Text of length(Kmer)
- This checks for each individual kmer that can possibly show up in Text
- Make sure to not extend past end of (Text - k)
* Check for each kmer in kmer Dictionary(hash table)
> If kmer is in the kmer Dictionary, increment it's frequency
> If kmer is not in the kmer Dictionary, add it to it
* Go through the Dictionary and find the maximum of the values
* Create List of Kmers in the Kmer Dictionary that have the maximum Frequency
* Return List
Alternative Ideas:
* Create
"""
#Inputs and Variables---------------------------------------
#-----------------------------------------------------------
'''File Input'''
with open('Data/rosalind_m4.txt') as inputData:
Text, k= [line.strip() for line in inputData.readlines()]
k = int(k)
inputData.close()
#-----------------------------------------------------------
'''Variables'''
lenText = len(Text)
#Stores the Kmers as the Key and the Frequency as the Value
kmerDict = {}
#-----------------------------------------------------------
'''Computing Frequent Kmers'''
#Iterates through all possible starting positions for a kmer
for i in xrange (lenText - k + 1):
#Define the Kmer
kmer = Text[i:i+k]
#Check if Kmer is in the Dict, Increment Freq if it is, Add it if its not
if kmer in kmerDict:
kmerDict[kmer] += 1
else:
kmerDict[kmer] = 1
i = i + k + 1
#Find the Maximum Freq in the Dict
max_freq = max(kmerDict.values())
#print max_freq
#Answer is list of kmers with max frequency
answer = [kmer for kmer, freq in kmerDict.items() if freq == max_freq]
print(' '.join(answer))
| true |
06dfb29376393349b6d438ab98e46d9b5ad71fb9 | ClayTaylor/learning-python-pycharm | /writing-to-files/learning-to-write-to-files.py | 899 | 4.1875 | 4 |
# employee_file = open("office.txt", "a") #Opening the office.txt file and Appending it (adding to the end of it).
# employee_file.write("\nKelly - Customer Service") #Writing to the file with a new line and inserting a new Employee named 'Kelly - Customer Service'
# print(employee_file) #Printing out the entire employee_file
# employee_file.close() #Closing the office.txt
employee_file = open("office.txt", "w") #Operning the office.txt file and writing to it. Writing to a file will delete any previous information on the file and will overwrite it with the new information.
#employee_file = open("office1.txt", "w") # Creates a new file to be written on.
employee_file.write("Kelly - Customer Services") #Writing to the file with a new line and inserting a new employee named 'Kelly - Customer Service'.
print(employee_file) # Printing out the file
employee_file.close() # Closing the file
| true |
8b53ade368bc1193027abb948a088df80a532271 | ClayTaylor/learning-python-pycharm | /building-a-guessing-game/guessing-game.py | 1,280 | 4.4375 | 4 |
secret_word = "milkshake" #Creating a Secret Word
guess = "" # Created a guess variable which is the input variable in the while loop.
guess_count = 0 # Variable counting the amount of guesses the user has input.
guess_limit = 5 # Variable counting the limit the user can input.
out_of_guesses = False # Variable detecting if the user has run out of guesses.
while guess != secret_word and not(out_of_guesses): # While Loop checking to see if the input is NOT equal to the secret word AND if the user has not run out of guesses.
if guess_count < guess_limit: # If Statement checking to see if the guess count remains lower than the guess limit.
guess = input("Enter your best guess: ") # input from the user
guess_count += 1 # Incrementing the guess count by one of the above remains true.
print("Guess Count: " + str(guess_count) + "/5")
else:
out_of_guesses = True # Once the user has reached their guess limit, then the out_of_guesses variable becomes true.
if out_of_guesses: # If True, then the following prints on the console and the user loses the game.
print("You have run out of guesses, and failed the game.")
else: # If false, then the user has guessed the correct secret word and has won the game.
print("You win!")
| true |
1d0ba35fe51c0817d6fd5c93d75110a15f276163 | Dvaraz/PY111 | /Tasks/a0_my_stack.py | 1,167 | 4.25 | 4 | """
My little Stack
"""
from typing import Any
stack = []
def push(elem: Any) -> None:
"""
Operation that add element to stack
:param elem: element to be pushed
:return: Nothing
"""
stack.append(elem)
print(elem)
return None
def pop() -> Any:
"""
Pop element from the top of the stack. If not elements - should return None.
:return: popped element
"""
if stack:
a = stack.pop(-1)
return a
else:
return None
def peek(ind: int = 0) -> Any:
"""
Allow you to see at the element in the stack without popping it.
:param ind: index of element (count from the top, 0 - top, 1 - first from top, etc.)
:return: peeked element or None if no element in this place
"""
print(ind)
if ind == 0:
return stack[-1]
elif ind > len(stack):
return None
else:
return stack[ind]
def clear() -> None:
"""
Clear my stack
:return: None
"""
stack.clear()
return None
if __name__ == '__main__':
push(7)
push(3)
push(5)
print(stack)
print(peek(-1))
print(stack)
clear()
print(stack)
| true |
2dc9fb665b05542b72623357693546535e12f5a8 | IvanM1987/Algorithm | /Lesson_2/2.5.py | 501 | 4.15625 | 4 | # 5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
# Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.
def tab(n):
if n < 128:
if n % 10 == 2:
print('\n')
print(f'{n}-\'{chr(n)}\'', end=' ')
n +=1
tab(n)
tab(32) | false |
461ccb5e3d72bb3b4c0a5aff3d91c9cbc14c852d | Anupriya1500/FPS1 | /day1.py | 858 | 4.34375 | 4 |
print("hello from anupriya")
print(2+3)
import math
print(math.sqrt(2))
math.sqrt(2)
math.pow(2,3)
input("enter the name: ")
myname =input("enter the name: ")
print(myname)
age=20.5
name="anu"
flag=True
type(flag)
value=None
type(value)
a = None
type(a)
age=input("enter the age: ")
"fork" - str
'forl' - str
"f" - str
'f'- str
int(2.3)
float(3)
age =int(age)
type(age)
str1="hey"
len(str1)
# single line comment
"""
multi line comment
xyubxu
"""
name=input("enter the name: ")
print(len(name))
# indexing or say slicing in python
name[0]
name[6]
name[0:5]
name[-2]
name[0:6:2]
name[0:9:1]
name[0:9:3]
name[1:]
name[:]
name
name[::2] # no start or end specified
name[::-1] # reverses the string
str1 = "corona virus"
str1[0:6]
str1[-9]
str1[-15]
str1[:::]
str1[::]
str1[:]
str1
#######
a = ['a', 'b']
type(a)
a += [1, 2, 3]
a
########## | false |
5f704355188f7660de1f1351ba1f020a8acd90e4 | coldhair/DetectionSystem | /tmp/temp038.py | 1,003 | 4.375 | 4 | # 计算当前月份的日期范围
# https://python3-cookbook.readthedocs.io/zh_CN/latest/c03/p14_date_range_for_current_month.html
from datetime import date, datetime, timedelta
import calendar
def get_month_range(start_date=None):
if start_date == None:
# date.replace(year, month, day):生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)
start_date = date.today().replace(day=1)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
end_date = start_date + timedelta(days=days_in_month)
return (start_date, end_date)
a_day = timedelta(days=1)
first_day, last_day = get_month_range()
while first_day < last_day:
print(first_day)
first_day += a_day
def date_range(start, stop, step):
while start < stop:
yield start
start += step
for d in date_range(datetime(2020, 5, 1), datetime(2020, 6, 1), timedelta(hours=6)):
print(d)
| false |
532bbf1faba344fc6dfea0ad87b1bec47868969b | raedeid/python-puzzle | /proplem9.py | 800 | 4.15625 | 4 | #A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#a2 + b2 = c2
#For example, 32 + 42 = 9 + 16 = 25 = 52.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
def is_triple_of_Pythagorean(a,b,c):#check if the 3 number has feature of the pythagorean trriple
if first**2+seconed**2==third**2:
return True
return False
for first in range(1,1000):#make roll for number under 1000 cause we need sumation equal 1000
for seconed in range (first,1000):
for third in range (seconed,1000):
if first+seconed+third==1000:
if is_triple_of_Pythagorean(first,seconed,third):
print (first*seconed*third)#print the product
break
| true |
fd064d9462d87f03fe5ac6dfc68bed270de86757 | BrunoOMelo/Leaning_Python | /ex07.py | 454 | 4.28125 | 4 | #declaring and formatting multiples variables as float.
n1 = float(input('Type the first note: '))
n2 = float(input('Type the second note: '))
#declaring "m" as average between "n1" an "n2".
m = (n1 + n2)/2
#formatting the output for the user.
print('Your average: {:.2f}' .format(m))
#declaring parameters for the output.
if(m >= 6):
print('You were approved!')
elif(m == 5):
print('You are recovery.')
else:
print('You were not approved')
| true |
33b280c164e91568b8ce5182e9b343319ff7ee2f | BrunoOMelo/Leaning_Python | /ex08.py | 285 | 4.125 | 4 | #declaring and formatting variable as float.
meter = float(input('Enter the value in meters: '))
centimeter = meter*100
milimeter = meter*1000
#presenting the result
print('Converted in centimeter: {:.2f}' .format(centimeter))
print('Converted in milimeter: {:.2f}' .format(milimeter)) | true |
a9e2c30661620b5705dfd1c0f329312d50ae9bd7 | aaazz47/LPTHW_for_Python3_EXs | /ex29_27.py | 2,985 | 4.28125 | 4 | print("Is 'not False' True?")
if not False:
print("Yes! is True!")
print("\n------------------------")
print("Is 'not True' True?")
if not True:
print("Yes! is True!")
print("\n------------------------")
print("Is 'True or True' True?")
if True or True:
print("Yes! is True!")
print("\n------------------------")
print("Is 'True or False' True?")
if True or False:
print("Yes! is True!")
print("\n------------------------")
print("Is 'False or True' True?")
if False or True:
print("Yes! is True!")
print("\n------------------------")
print("Is 'False or False' True?")
if False or False:
print("Yes! is True!")
print("\n------------------------")
print("Is 'True and True' True?")
if True and True:
print("Yes! is True!")
print("\n------------------------")
print("Is 'True and False' True?")
if True and False:
print("Yes! is True!")
print("\n------------------------")
print("Is 'False and True' True?")
if False and True:
print("Yes! is True!")
print("\n------------------------")
print("Is 'False and False' True?")
if False and False:
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (True or True)' True?")
if not (True or True):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (True or False)' True?")
if not (True or False):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (False or True)' True?")
if not (False or True):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (False or False)' True?")
if not (False or False):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (True and True)' True?")
if not (True and True):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (True and False)' True?")
if not (True and False):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (False and True)' True?")
if not (False and True):
print("Yes! is True!")
print("\n------------------------")
print("Is 'not (False and False)' True?")
if not (False and False):
print("Yes! is True!")
print("\n------------------------")
print("Is '1 != 1' True?")
if 1 != 1:
print("Yes! is True!")
print("\n------------------------")
print("Is '1 != 0' True?")
if 1 != 0:
print("Yes! is True!")
print("\n------------------------")
print("Is '0 != 1' True?")
if 0 != 1:
print("Yes! is True!")
print("\n------------------------")
print("Is '0 != 0' True?")
if 0 != 0:
print("Yes! is True!")
print("\n------------------------")
print("Is '1 == 1' True?")
if 1 == 1:
print("Yes! is True!")
print("\n------------------------")
print("Is '1 == 0' True?")
if 1 == 0:
print("Yes! is True!")
print("\n------------------------")
print("Is '0 == 1' True?")
if 0 == 1:
print("Yes! is True!")
print("\n------------------------")
print("Is '0 == 0' True?")
if 0 == 0:
print("Yes! is True!")
| false |
823cfbd864275c620eb0f74dd3cce51b929318f4 | AmeyVanjare/PythonAssignments | /LabAssignment/LabAssignmentQ11.py | 280 | 4.15625 | 4 | def find_longest_word(lst):
max=""
for i in lst:
if len(i)>len(max):
max=i
return max
if __name__=="__main__":
lst=["Alpha","Beta","gamma","delta","Alexander"]
res=find_longest_word(lst)
print("Lonest word is ",res)
| false |
903399634a23ecbf00a5f28be445565c7aa6fc61 | PrashilAlva/Programs | /Practice/Data Analytics (Heraizen)/Assignment/Set 2/q2.py | 823 | 4.15625 | 4 | dictio=dict()
while(True):
choice=int(input("1.Add Student Details\n2.Display Students\n3.Search Student\n4.Exit\n"))
if choice==1:
student_id=input("Enter the Student ID:")
student_name=input("Enter the Student Name:")
dictio[student_id]=student_name
print("Student Detail Entered Successfully!")
elif choice==2:
if len(dictio)==0:
print("Dictionary is empty!")
else:
for ele in dictio:
print(ele,":",dictio[ele])
elif choice==3:
query=input("Enter the Student ID:")
if query not in dictio:
print("Entered Student ID does not exist...")
else:
print(query,":",dictio[query])
elif choice==4:
exit()
else:
print("Please Enter the valid option...")
| true |
4aac2cd85a8b78ee9b64c8a3a9741c11a553def9 | sjhhh3/Leetcode | /Leecode/leetcode720-2.py | 308 | 4.125 | 4 | words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
def longestWord(words):
valid = set([""])
for word in sorted(words):
if word[:-1] in valid:
a = word[:-1]
valid.add(word)
return max(sorted(valid), key=lambda x: len(x))
print(longestWord(words))
| true |
f4d46415e0da23aad11a322c6bde4b2a56dd28b7 | CodeCreed21/Python1 | /name.py | 206 | 4.15625 | 4 | name=input("Name: ")
#print("Hello " + name)
#Riga 2 puo' avere una diversa sintassi
print(f"Hello, {name}") #f= formatted string: autorizza ad inserire il valore di una variabile all'interno della stringa | false |
9e7a8910969d5e0ac9d1046bb841fb43416ff623 | shivaniarbat/pytorch-101 | /Linear-Models/simple-linear-model.py | 380 | 4.125 | 4 | """
To learn to write a simple linear model in pytorch
"""
import torch
# set weight and bias
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(-1.0, requires_grad=True)
# define the forward function for the linear model
def forward(x):
yhat = w*x + b
return yhat
# define X
x = torch.tensor([[1.0],[2.0]])
# compute yhat
yhat = forward(x)
print("yhat",yhat)
| true |
93930851fe28066d6a2e42bc781044d914701394 | danlenguyen2201/BTVN-LND | /BTVN/For test.py | 2,052 | 4.3125 | 4 | # items.remove("Phở gánh")
# print(items)
#
# items.pop(3)
# print(items)
items = ["T-shirt","Jeans","Sweater","Pants","Gun","Sword"]
print("Welcome t’o our shop, what do you want ?")
print("Down here are the choices :D")
print("1: Add new item to the shop")
print("2: See our items")
print("3: Update an item name")
print("4: Delete an item in the shop")
print("5: Exit")
print("Please enter a number!")
loop_continue = True
while loop_continue:
choice = int(input(">> "))
def print_items():
item_no = 1
for item in items:
print("#", end="")
print(item_no, end =". ")
print(item)
item_no += 1
if choice == 1:
new_item = input("Enter the new item name:")
items.append(new_item)
print("The items list have been update to this")
print(items)
print("Anything else?")
print_items()
elif choice == 2:
print("Here are our items")
print_items()
print("Anything else?")
print_items()
elif choice == 3:
print_items()
position = int(input("What position ?"))
new_item_name = input("Please enter the new name:")
items[position - 1] = new_item_name
print(items)
print("The name of the item have been updated")
print("Anything else?")
print_items()
elif choice == 4:
print_items()
position = int(input("Qhat position do you want to delete ?"))
items.pop(position - 1)
print("The list have been updated")
print(items)
print("Anything else?")
print_items()
elif choice == 5:
print("Thank you for doing business with us,good bye and have a good day! ")
loop_continue = False
else:
print("Sorry but you have choosed the wrong choice, please choose again!")
print("1: Add new item to the shop")
print("2: See our items")
print("3: Update an item name")
print("4: Delete an item in the shop")
print("5: Exit") | true |
00665b71ffc7a3fa1d85a794fc3f49037a0c62f1 | philipwoodward/Practicals | /Prac01/tarrifElectricityBillEstimator.py | 710 | 4.15625 | 4 | """
Program to calculate and display
the electricity bill. Inputs will be price per kWh in cents,
daily use in kWh and the number of days in the billing period
"""
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = 1
while tariff == 1:
tariff = int(input("Enter which tariff please - 11 or 31: "))
if tariff == 11:
tariff = TARIFF_11
elif tariff == 31:
tariff = TARIFF_31
else:
tariff = 1
print(tariff)
daily_use = float(input("Enter the kilowatt hours of electricity use per day: "))
number_days = int(input("Enter the number of days in the billing period: "))
print("The estimated electricity bill is $", round(tariff * daily_use * number_days,2))
print("Thank you.")
| true |
1f741e16f27b7f0bb51ac25d056b6fd9903f1b91 | ahujagaurav/Python | /Basic Bank Account.py | 1,086 | 4.125 | 4 |
a = {'Name': 'gaurav', 'balance': 2755,'A/C':1}
b = {'Name': 'Akshay', 'balance': 2734,'A/C':2}
c = {'Name': 'Nikhil', 'balance': 2772,'A/C':3}
d = {'Name': 'Aditya', 'balance': 2712,'A/C':4}
final = {
1:a,
2:b,
3:c,
4:d,
}
loginchoice = raw_input("Enter your choice")
if loginchoice=='login':
choice = input("What is your username? ")
choice2 = input("What is your password? ")
if choice==choice2:
print final[choice]
else:
print "The username or password you entered is incorrect. Please try again or register."
elif loginchoice=='exit':
print "You choose to exit! Bye Bye"
elif loginchoice=='Transfer':
transfer= int (input("Enter the amount you want to transfer"))
account= int (input("Enter your user Account Number"))
if account not in final:
print "Wrong account number"
elif account in final:
a=final['Bal']-transfer
b=final[account]['Bal']+transfer
print "Transaction Successfull "
else:
print "Wrong account! Please try again"
else :
print "The choice you entered is wrong! Please try again"
#!/usr/bin/python
| true |
a4a32ea7c147dd1e9396313b085b6631453ac634 | Shouraya/Computatuional-Statistics-Lab-Assignment | /Assignment 1/1.py | 350 | 4.15625 | 4 | #input check whether entered digit or not
def num():
num = ''
while not num.isdigit() :
num = input("Enter number: ")
return int(num)
num1 = num()
num2 = num()
print('The addition gives: ',num1+num2)
print('The substraction gives: ',num1-num2)
print('The multiplication gives: ',num1*num2)
print('The division gives: ',num1/num2) | true |
c58d26d9162496575a94a96c338385ce33e30432 | pzy636588/wodedaima | /赋值运算符(比较运算符).py | 759 | 4.25 | 4 | python=98 #定义变量,存储python的分数
english=92 #定义变量,存储english的分数
c=89 #定义变量,存储c语言的分数
sub=python-c #计算python语言和c语言的分数之差
avg=(python+english+sub)/3 #计算平均成绩
avg=int(avg) #字符串转换
print(type(avg))
sum=python+english+c #计算总分
print(type(sum))
print("python课程与c语言课程分数之差:"+str(sub)+"分\n")
print("课程的平均分:"+str(avg)+"分\n")
print("课程总分:"+str(sum)+"分\n")
print("python="+str(python)+"english="+str(english)+"c="+str(c)+"\n")
print("english>pthon分数:"+str(english>python)+"\n")
| false |
4ffc0b2a5bb68e9b5748ade74e5b43e686a22996 | pzy636588/wodedaima | /算术运算符.py | 717 | 4.25 | 4 | python=98 #定义变量,存储python的分数
english=92 #定义变量,存储english的分数
c=89 #定义变量,存储c语言的分数
sub=python-c #计算python语言和c语言的分数之差
avg=(python+english+sub)/3 #计算平均成绩
avg=int(avg) #字符串转换
print(type(avg))
sum=python+english+c #计算总分
print(type(sum))
print("python课程与c语言课程分数之差:"+str(sub)+"分\n")
print("课程的平均分:"+str(avg)+"分\n")
print("课程总分:"+str(sum)+"分\n")
print(2**5) #幂
print(2//8) #余数
print(3%7)
| false |
45b5c94aa09b14f959a346fe7a1016f59fb1af63 | Flaeros/leetcode | /src/educative/fibonacci_numbers/fibonacci_numbers_memo.py | 888 | 4.15625 | 4 | def calculateFibonacci(n):
memo = [-1 for _ in range(n + 1)]
return calculateFibonacci_rec(memo, n)
def calculateFibonacci_rec(memo, n):
if n < 2:
return n
if memo[n] == -1:
memo[n] = calculateFibonacci_rec(memo, n - 1) + calculateFibonacci_rec(memo, n - 2)
return memo[n]
def main():
print("0th Fibonacci is ---> " + str(calculateFibonacci(0)))
print("1th Fibonacci is ---> " + str(calculateFibonacci(1)))
print("2th Fibonacci is ---> " + str(calculateFibonacci(2)))
print("3th Fibonacci is ---> " + str(calculateFibonacci(3)))
print("4th Fibonacci is ---> " + str(calculateFibonacci(4)))
print("5th Fibonacci is ---> " + str(calculateFibonacci(5)))
print("6th Fibonacci is ---> " + str(calculateFibonacci(6)))
print("7th Fibonacci is ---> " + str(calculateFibonacci(7)))
if __name__ == '__main__':
main()
| false |
f40a3551938b5492ce28f5ec2109d7fc5a826b25 | pbaldera/practice | /restaurant_seating.py | 312 | 4.40625 | 4 | print("Welcome to family restaurant!")
number_of_people = input("How many people are in the dinner group?")
number_of_people = int(number_of_people)
if number_of_people > 8:
print("Your table is not ready, you will have to wait to be seated")
else:
print("Your table is ready, see a host to be seated")
| true |
97ca2d35faf868b8bc07d6be7ea822854426194c | pavelburundukov/algorithms | /homework2/exercise8.py | 708 | 4.28125 | 4 | # 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
n = int(input("Введите кол-во чисел: "))
target = int(input("Введите цифру для поиска: "))
s = 0
for i in range(0,n):
x = int(input("Введите число: "))
for j in str(x):
if j == str(target):
s += 1
print("Цифра " + str(target) + " встречается " + str(s) + " раз.")
| false |
1c87c9368eee093fd9aebda64b20bb75c0109575 | pavelburundukov/algorithms | /homework1/exercise2.py | 571 | 4.21875 | 4 | # 2. Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6. Выполнить над числом 5 побитовый сдвиг вправо и влево # на два знака. Объяснить полученный результат.
x = 5
y = 6
print(bin(x))
print(bin(y))
print("x & y: " + bin(x & y)) # and
print("x | y: " + bin(x | y)) # or
print("x ^ y: " + bin(x ^ y)) # xor
print("~x: " + bin(~x)) # not
print("x >> 3: " + bin(x >> 3))
print("x << 3: " + bin(x << 3))
| false |
1e844f566833fb45072658289efe0877f1014052 | RishabhGoswami/Algo.py | /Top view of tree.py | 1,923 | 4.1875 | 4 | class Node:
def __init__(self, key=None, left=None, right=None):
self.key = key
self.left = left
self.right = right
# Recursive function to perform preorder traversal on the tree and fill the dictionary.
# Here, the node has `dist` horizontal distance from the tree's root,
# and the level represents the node's level.
def printTop(root, dist, level, dict):
# base case: empty tree
if root is None:
return
# if the current level is less than the maximum level seen so far
# for the same horizontal distance, or if the horizontal distance
# is seen for the first time, update the dictionary
if dist not in dict or level < dict[dist][1]:
# update value and level for current distance
dict[dist] = (root.key, level)
# recur for the left subtree by decreasing horizontal distance and
# increasing level by 1
printTop(root.left, dist - 1, level + 1, dict)
# recur for the right subtree by increasing both level and
# horizontal distance by 1
printTop(root.right, dist + 1, level + 1, dict)
# Function to print the top view of a given binary tree
def printTopView(root):
# create a dictionary where
# `key` —> relative horizontal distance of the node from the root node, and
# `value` —> pair containing the node's value and its level
dict = {}
# perform preorder traversal on the tree and fill the dictionary
printTop(root, 0, 0, dict)
# traverse the dictionary in sorted order of keys and print the top view
for key in sorted(dict.keys()):
print(dict.get(key)[0], end=' ')
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.right = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.right.left.left = Node(7)
root.right.left.right = Node(8)
printTopView(root)
| true |
0636720d8b0a18e4ea05d954f81ddb8f18b65f10 | mayakeren/DevOps | /Classes/Class 17.02 -Python.py | 1,975 | 4.125 | 4 | print("Hi_Maya")
x = 10
y = 5.1
z = "Maya"
print(x)
print(y)
print(z)
print(5 + 4)
print(x, z)
print(str(x) + z)
f = 4
g = 7
print(f * g)
print(f / g)
print(f - g)
# combining string with numeric, use str or comma.
print("My age is:" + str(36))
if x > 2:
print('x is bigger')
# if the first doesn't exist- it won't check the second.
if 2 < x:
print('2 is smaller')
if x > 2:
print('x is bigger')
if 11 < x:
print('11 is smaller')
a = 15
b = 2
# Multi condition - which will be evaluated in the same statement:
# Below both condition have to return true using *and*
if (a > b and a >10):
print('a is bigger than b and 10')
# Below only one condition have to return true using *or*
if (a > b or a > 10):
print('a is bigger than b and 10')
# Else can be added to if condition
if x > 2:
print('x is bigger')
else:
print('x is smaller')
m = 52
n = 99
if (m > n):
print(m)
else:
print(n)
if (m > n):
print('m is bigger')
else:
print('n is bigger')
if (m > n and m > 20):
print('success')
if ((m * 2) > (n / 5)):
print('great math')
# Elif always comes after if. else comes after both. as soon as one condition is met, the rest will not be tested.
a = 1
b = 2
if a >b:
print('a is bigger')
elif a==b:
print('equals')
elif a!=b:
print('not equals')
else:
print('none')
# Keyboard input. Makes the program keep running and waiting for input + enter in order to print.
name = input('Please enter name: ')
print('Hi', name)
number = int(input('What is your age? '))
if (number > 18):
print('Adult')
password ="12345"
user_password = input('Enter your password ')
if user_password==password:
print('Logged in')
elif user_password!=password:
print('Access denied')
Age = int(input('How old are you? '))
Hight- int(input('How tall are you? '))
if Age > 12 and Hight > 160:
print('OK') | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.