blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
66510521396ed5c733e85cc1cd114b213585fa67 | Ankita-Dake/PythonRegularExpression | /RegularExpression.py | 1,282 | 4.25 | 4 | # using search method
import re
s = "Hello from python"
i = re.search("from", s)
if (i):
print("string match")
else:
print("No match found")
# ^ start with string
a = "This is regular expression"
j = re.search("^This", a)
if (j):
print("string match")
else:
print("No match found")
# $ end with string
result = re.search("python$", "Hello from python")
if (result):
print('Match found')
else:
print('not found')
# using findall method
b = "Hello from python 3.9 version, This is regular expression"
str = re.findall("[a-z]", b) # lower case
str3 = re.finditer('[a-z]', b)
str1 = re.findall("[A-Z]", b) # upper case
str2 = re.findall("[0-9]", b) # digits
print(str3)
print(str)
print(str1)
print(str2)
# using compile method
pattern = re.compile('sir')
res = pattern.findall('hello sir nit ')
print(res)
r = pattern.search('sir')
print(r)
# using sub method
sub1 = "hello sir this is python"
res1 = re.sub('sir', 'mam', sub1)
print(res1)
sub2 = 'hello sir this is python and hello sir good morning'
res2 = re.subn('sir', 'mam', sub2)
print(res2)
# using split method
res3 = re.split(' ','hi felix it')
print(res3)
res4 = re.split('sir', 'hi sir from felix it')
print(res4)
res5 = re.split(' ', ' hi sir python is good', maxsplit=3)
print(res5)
| false |
1d4b7b925e4c71c3bde9b6e62b7ef864f041eb33 | 2amitprakash/Python_Codes | /Grokking_Algo/quicksort.py | 494 | 4.125 | 4 | import random
def quicksort(list):
if len(list) < 2:
return list
else:
pi = random.randint(0,len(list)-1)
#pi = 0
print ("The list is {l} and random index is {i}".format(l=list,i=pi))
pivot = list.pop(pi)
less = [i for i in list if i <= pivot]
more = [i for i in list if i > pivot]
return quicksort(less) + [pivot] + quicksort(more)
#End of function
l=[2,3,6,7,4,6,9,11,-1,5]
print ("The sorted list is - ",quicksort(l))
| true |
1b076c0cac0d11470b6ee48b998ba73b20182317 | TechyAditya/COLLEGE_ASSIGNMENTS | /Python/chapter4/list_methods.py | 395 | 4.1875 | 4 | l1=[1,8,9,5,6,6] #can have same elemnets repeatedly
l1.sort() #arranges in ascending order
print(l1)
l1.reverse() #reverse the list elements
print(l1)
l1.append(10) #adds element at the end of the list
print(l1)
l1.insert(3,69) #adds element at the index mentioned, but doesn't removes the elements
print(l1)
l1.pop(2)# #removes the index
print(l1)
l1.remove(6) #removes the element
print(l1) | true |
57e8eda341a70e86b185c04304d6d73d814737b6 | AkashKumarSingh11032001/100-Days-Python-Bootcamp-By-AngelaYu | /Day 3 - Beginner - Control Flow and Logical Operators/Lec_code.py | 2,300 | 4.21875 | 4 | # 1
# if-else
# height = eval(input("Enter your height: "))
# if(height > 120):
# print("Sell Ticket")
# else:
# print("Not Eligible")
# 2
# ex-3.1
# num = eval(input("Enter Number. : "))
# if(num % 2 == 0):
# print("Even Num.")
# else:
# print("Odd Num.")
# 3
# nested If-else
# height = eval(input("Enter your height: "))
# age = eval(input("Enter your age: "))
# if(height > 120):
# if(age < 18):
# print("$7 ")
# else:
# print("$12")
# else:
# print("Not Eligible")
# 4
# ex-3.2
# BMI 2.0
# height = float(input("Enter your height in m: "))
# weight = float(input("Enter your weight in kg: "))
# #bmi = round(weight / height**2)
# bmi = 25
# if bmi < 18.5:
# print(f"Your bmi is {bmi}, you are underweight.")
# elif bmi < 25:
# print(f"Your bmi is {bmi}, you have a normal weight.")
# elif bmi < 30:
# print(f"Your bmi is {bmi}, you are overweight.")
# elif bmi < 35:
# print(f"Your bmi is {bmi}, you are obese.")
# else:
# print(f"Your bmi is {bmi}, you are clinically obese.")
# ex-3.3
# year = eval(input("Enter Year: "))
# if(year % 4 == 0 or year % 100 == 0 or year % 400 == 0):
# print("Leap Year")
# else:
# print("Not a Leap year")
# 5
# Multiple If statement
# 6
# ex-3.3
# print("Welcome to Python Pizza Deliveries!")
# size = input("What size pizza do you want? S, M, or L ")
# add_pepperoni = input("Do you want pepperoni? Y or N ")
# extra_cheese = input("Do you want extra cheese? Y or N ")
# cost = 0
# if(size == 'S'):
# if(add_pepperoni == 'Y'):
# cost += 17
# else:
# cost += 15
# elif(size == 'M'):
# if(add_pepperoni == 'Y'):
# cost += 23
# else:
# cost += 20
# elif(size == 'L'):
# if(add_pepperoni == 'Y'):
# cost += 28
# else:
# cost += 25
# if(extra_cheese == 'Y'):
# cost += 1
# print(f"Total price you have to pay: ${cost}")
# 10
# ex-3.5
# Love Calulator
my_name = input("Enter Your name: ")
crush_name = input("Enter Crush name: ")
name = (my_name + crush_name).lower()
print(my_name +" weds "+crush_name)
T,R,U,E = name.count('t'),name.count('r'),name.count('u'),name.count('e')
L,O,V,E = name.count('l'),name.count('o'),name.count('v'),name.count('e')
print(f"Chance Of Marriage: {T+R+U+E}{L+O+V+E}%") | false |
f7789ce8986996cdbaf4b06dcb527077538b0170 | RUSTHONG/Algorithm | /pythondev/bubble_sort.py | 372 | 4.15625 | 4 | def bubble_sort(List):
for t in range(len(List)-1, 0, -1):
for i in range(t):
if List[i] > List[i+1]:
List[i], List[i+1] = List[i+1], List[i]
print(List)
if __name__ == "__main__":
List = input("Please type in your list: ").split(",")
List = [int(a) for a in List]
print(List)
bubble_sort(List)
| false |
5e9f0ec62bdb1ee1c60a53b921d14741fded440d | I-bluebeard-I/GB_py_algorithms | /less07_task01.py | 1,000 | 4.1875 | 4 | """
1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, заданный случайными числами на
промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы. Сортировка должна быть реализована
в виде функции. По возможности доработайте алгоритм (сделайте его умнее).
"""
from random import randint
def func_srt(ary):
i = 0
while i < len(ary):
for j in range(len(ary) - (i + 1)):
if ary[j] < ary[j + 1]:
ary[j], ary[j + 1] = ary[j + 1], ary[j]
i += 1
return ary
a = []
for i in range(10):
a.append(randint(-100, 100))
print(f'Массив до сортировки: {chr(9)*2}{a}')
print(f'Массив после сортировки: {chr(9)}{func_srt(a)}')
| false |
c902d56fd3a438b0e7bab5d0df826422979ea800 | HarryBaker/Fuka | /cleanTxtFiles.py | 1,960 | 4.1875 | 4 | # A program that cleans text files when given raw input in the following manner:
# Remove all characters except letters, spaces, and periods
# Convert all letters to lowercase
__author__ = 'loaner'
from sys import argv
class Cleaner:
def __init__(self, input):
raw_file_name = raw_input(input);
file_name = raw_file_name + ".txt";
# Access the raw file
f = open(file_name, "r")
f2 = open((raw_file_name + "_intermediary.txt"), "w")
# First cleanup (by character):
# Cleaning every character that is not a letter, space, or period
# Converting all letters to lowercase
while 1:
char = f.read(1)
if not char: break
if char.isalpha() or char.isspace() or char == '.' : f2.write(char.lower());
f2 = open((raw_file_name + "_intermediary.txt"), "r")
f3 = open((raw_file_name + "_clean.txt"), "w")
wrote_word = False
# Second cleanup:
# Remove unneccessary spaces and newlines longer than one character that was not possible in the previous clean up step
# Remove words that are shorter than 2 characters
for line in f2:
line = line.rstrip()
words = line.split()
for word in words:
wrote_word = False
if len(word)>2:
f3.write(word + " ")
wrote_word = True
if(wrote_word):
f3.write("\n")
f.close()
f2.close()
f3.close()
# Works Cited:
# http://www.tutorialspoint.com/python/python_files_io.htm
# http://learnpythonthehardway.org/book/ex15.html
# http://www.java2s.com/Code/Python/File/Openafileandreadcharbychar.htm
# http://pymbook.readthedocs.org/en/latest/file.html
# http://stackoverflow.com/questions/29359401/open-a-file-split-each-line-into-a-list-then-for-each-word-on-each-line-check
| true |
0ffbe7a1cc9c186c1043d0b683f19ba6499a1602 | onestarshang/leetcode | /validate-binary-search-tree.py | 1,814 | 4.1875 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/validate-binary-search-tree/
Given a binary tree, determine if it is a valid binary search tree (BST).\n\nAssume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.\nOJ's Binary Tree Serialization:\nThe serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.\n
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
'''
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
if not root:
return True
is_valid, _, _ = self.is_valid(root)
return is_valid
def is_valid(self, node):
if not node.left and not node.right:
return True, node.val, node.val
is_valid = True
min_val = max_val = node.val
if node.left:
left_valid, left_min, left_max = self.is_valid(node.left)
is_valid = is_valid and left_valid and left_max < node.val
min_val = left_min
if node.right:
right_valid, right_min, right_max = self.is_valid(node.right)
is_valid = is_valid and right_valid and node.val < right_min
max_val = right_max
return is_valid, min_val, max_val
| true |
f3634048b65198301168cf657d3e7ffa463ba159 | onestarshang/leetcode | /decode-string.py | 1,719 | 4.125 | 4 | '''
https://leetcode.com/problems/decode-string/
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
'''
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
def decode(start):
r = ''
i = start
while i < n:
c = s[i]
if c.isdigit():
num = 0
while s[i].isdigit():
num = num * 10 + int(s[i])
i += 1
assert s[i] == '['
w, end = decode(i + 1)
r += w * num
i = end
elif c == ']':
return r, i
else:
r += c
i += 1
return r, i
r, _ = decode(0)
return r
if __name__ == '__main__':
f = Solution().decodeString
assert f('') == ''
assert f("3[a]2[bc]") == "aaabcbc"
assert f("3[a2[c]]") == "accaccacc"
assert f("2[abc]3[cd]ef") == "abcabccdcdcdef"
| true |
0b7d06e83d9a32417b0ef408ffcc340960bf268b | onestarshang/leetcode | /convert-a-number-to-hexadecimal.py | 1,277 | 4.625 | 5 | # coding: utf-8
'''
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
'''
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return '0'
if num < 0:
num += 1 << 32
digits = '0123456789abcdef'
base = len(digits)
r = ''
while num:
r = digits[num % base] + r
num /= base
return r
if __name__ == '__main__':
f = Solution().toHex
assert f(0) == '0'
assert f(26) == '1a'
assert f(-1) == 'ffffffff'
| true |
351202ef5ebd3c6de3fc46c446fc1c9ff4d8efc6 | onestarshang/leetcode | /fraction-to-recurring-decimal.py | 2,300 | 4.125 | 4 | '''
https://leetcode.com/problems/fraction-to-recurring-decimal/
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
Hint:
No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?
Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
'''
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
sign = 1
if numerator < 0:
sign = -sign
numerator = -numerator
if denominator < 0:
sign = -sign
denominator = -denominator
int_part = numerator / denominator
numerator = numerator % denominator * 10
p = -1
r = []
ns = [numerator]
while numerator != 0:
x = numerator / denominator
r.append(x)
numerator = numerator % denominator * 10
try:
k = ns.index(numerator)
p = k
break
except Exception:
pass
ns.append(numerator)
s = ('-' if sign < 0 and (r or int_part) else '') + str(int_part)
r = map(str, r)
if r:
if p == -1:
s += '.' + ''.join(r)
else:
s += '.' + ''.join(r[:p]) + '(' + ''.join(r[p:]) + ')'
return s
if __name__ == '__main__':
f = Solution().fractionToDecimal
assert f(-2147483648, 1) == '-2147483648'
assert f(0, -5) == '0'
assert f(-50, 8) == '-6.25'
assert f(1, 333) == '0.(003)'
assert f(1, 2) == '0.5'
assert f(2, 1) == '2'
assert f(1, 8) == '0.125'
assert f(1, 7) == '0.(142857)'
assert f(2, 3) == '0.(6)'
assert f(4, 9) == '0.(4)'
assert f(4, 333) == '0.(012)'
| true |
12383bafbb9af46d9e220928ccb9746ba4725084 | onestarshang/leetcode | /find-all-anagrams-in-a-string.py | 1,569 | 4.125 | 4 | '''
https://leetcode.com/problems/find-all-anagrams-in-a-string/
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
'''
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
m = len(p)
cp = [0 for i in xrange(26)]
for c in p:
cp[ord(c) - 97] += 1
cs = [0 for i in xrange(26)]
result = []
for i, c in enumerate(s):
cs[ord(c) - 97] += 1
if i >= m - 1:
if all(cp[j] == cs[j] for j in xrange(26)):
result.append(i - m + 1)
cs[ord(s[i - m + 1]) - 97] -= 1
return result
if __name__ == '__main__':
f = Solution().findAnagrams
assert f('cbaebabacd', 'abc') == [0, 6]
assert f('abab', 'ab') == [0, 1, 2]
| true |
2924fb03143cf10abacfe8f59a64be61300e8f1a | onestarshang/leetcode | /number-of-1-bits.py | 660 | 4.15625 | 4 | # coding: utf-8
'''
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
'''
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ans = 0
while n:
if n & 1:
ans += 1
n >>= 1
return ans
if __name__ == '__main__':
f = Solution().hammingWeight
assert f(11) == 3
| true |
366baaa2535d13166583420c45c6a80229d810ef | onestarshang/leetcode | /zigzag-conversion.py | 1,235 | 4.25 | 4 | '''
https://leetcode.com/problems/zigzag-conversion/
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
'''
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or numRows > len(s):
return s
d = ['' for i in xrange(numRows)]
x = 0
dx = 1
for c in s:
d[x] += c
if x == numRows - 1:
dx = -1
elif x == 0:
dx = 1
x += dx
return ''.join(d)
if __name__ == '__main__':
f = Solution().convert
assert f("PAYPALISHIRING", 3) == "PAHNAPLSIIGYIR"
assert f("PAYPALISHIRING", 1) == "PAYPALISHIRING"
assert f("PAYPALISHIRING", 2) == "PYAIHRNAPLSIIG"
assert f("zcdffagygmalkzfmqavtzeqfjtmdxvvwxbefdmfjyfukhcwxctqdziliexlbtjzsmfxprfzqmvctxbqcuifurqcvqqyjzxbnfbcwidouzrowsgyopgiiyndoddxeabrhevgmzuiynywhfxywdggbvlsaopgqszyyvekuavuqtqxanxysgewbpocdfkwakuyfalbagvqblqcbnavvhrxyhbeplapvwncwydwgypimhmnwmksvcpulsyadapbwfdsdjqmhfutmgilutdqxumimmlrmauifyalhqxqytmmzuxtpalouzxilkaxkufsuhfdacwyvikwekrukfihehpqtrpeoxyiedoehkeesrcybtunyfudmmvgfkmthmcorsuaczewsiutbpgcudhircqwoeqyqumjogjqhpozxiubzddvikezowxebpctlqdzzmrgcfibqecrhhnrtrshnsoqhqkvhnwizoqdvahnflhotugmnawcsktccdxlstttjkxhkgwrrdgkzozmoxphjkllpizhduapgzwrfukzaslzgkoxjfgsprgezflezntgnrzumltoefnkpdhbiptzgzdhgqmighqtzpnnchbgmqrduaeesaeybjiiawqgdgbcxorzxuillbrhdxlvxpwzbejdazlfhmkgcbhcwpnjqequcdrbvncwrlztmkzvyjbaklciaqrtwhpangeiugensdhgpgcnrfnbqsktkdogndjalniftmvnrcuikyvbdkeueqnoubxhgghrvrzofueyyagiydlbpp", 789)
| true |
83c3d2036ad237a76c79a6a69ef638acd4a01b1e | onestarshang/leetcode | /balanced-binary-tree.py | 1,062 | 4.15625 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
is_balance, _ = self.is_balance(root)
return is_balance
def is_balance(self, node):
if node is None:
return True, 0
left_balance, left_dep = self.is_balance(node.left)
right_balance, right_dep = self.is_balance(node.right)
is_balance = (left_balance and
right_balance and
abs(left_dep - right_dep) <= 1)
return is_balance, max(left_dep, right_dep) + 1
| true |
e4e68fbe07641281facb7986ebd93b855e85c967 | onestarshang/leetcode | /insertion-sort-list.py | 1,308 | 4.25 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/insertion-sort-list/
Sort a linked list using insertion sort.
'''
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head or not head.next:
return head
p = head
new_head = head.__class__(0)
tail = None
while p:
node = p.__class__(p.val)
if tail and node.val > tail.val:
tail = self.insert(tail, tail, node)
else:
tail = self.insert(new_head, tail, node)
p = p.next
return new_head.next
def insert(self, head, tail, node):
current = head.next
last = head
while current:
if current.val > node.val:
break
last = current
current = current.next
if last:
last.next = node
node.next = current
return node if current is None else tail
if __name__ == "__main__":
from datetime import datetime
from utils import ListNode
head = ListNode.make_list([3, 2, 1])
st = datetime.now()
p = Solution().insertionSortList(head)
# print p.to_list()
print datetime.now() - st
| true |
9dce19d97804637a281134363814828aba1d17a5 | maxkajiwara/Sorting | /project/iterative_sorting.py | 1,237 | 4.28125 | 4 | # Complete the selection_sort() function below in class with your instructor
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
cur_index = i
smallest_index = cur_index
# find next smallest element
for j in range(cur_index, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
# swap
temp = arr[smallest_index]
arr[smallest_index] = arr[cur_index]
arr[cur_index] = temp
return arr
# TO-DO: implement the Insertion Sort function below
def insertion_sort(arr):
# return arr for length 0 or 1
if len(arr) < 2:
return arr
# loop through elements starting from second element
for i in range(1, len(arr)):
cur_index = i
temp = arr[cur_index]
#
while cur_index > 0 and temp < arr[cur_index - 1]:
arr[cur_index] = arr[cur_index - 1]
cur_index -= 1
arr[cur_index] = temp
print(arr)
return arr
# STRETCH: implement the Bubble Sort function below
def bubble_sort(arr):
return arr
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
| true |
3d46063fcec3096eaa699de7d89894b398974fa4 | PetosPy/rock_paper_scissor | /Rock_Paper_Scissors.py | 1,342 | 4.25 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
print("Welcome to the game of Rock, Paper, Scissors.")
print("\n")
option = int(input("Type 0 for Rock, 1 for Paper or 2 for Scissors: \n "))
while option not in range(0,3):
option = int(input("Type 0 for Rock, 1 for Paper or 2 for Scissors: \n "))
computer = random.randint(0,2)
game_image = [rock, paper, scissors]
#PLAYER CHOICE
print(game_image[option])
#COMPUTER LOGIC
print("computer chose: ")
print(game_image[computer])
# 0 == ROCK
# 1 == PAPER
# 2 == SCISSORS
# COMPARE THE CHOSEN OPTIONS
if option == 0 and computer == 2:
print("You Win")
elif option == 2 and computer == 0:
print("You Lose")
elif option == 1 and computer == 0:
print("You win")
elif option == 0 and computer == 1:
print("You Lose")
elif option == 2 and computer == 1:
print("You win")
elif computer == option:
print("Its a Draw")
else:
print("Wrong choice, you lose")
| false |
91f57de49217b1186f6990ee5b15826c493ef99b | janagodbole/ProblemSet12 | /ProblemSet8.py | 1,375 | 4.125 | 4 | number_list = [5,3,7]
print("negative")
number_list[0] = number_list[0] * -1
[print(number_list)]
print("10 added")
number_list.append(10)
print(number_list)
print("16 @ 2")
number_list = number_list[0:2] + [16] + number_list[2:]
print(number_list)
print("letter @ 1 removed")
number_list.remove(number_list[1])
print(number_list)
print("temporarily sorted number list")
print(sorted(number_list))
print("Now the list is back to normal")
print(number_list)
print("sort list permanently")
number_list.sort()
print(number_list)
print("Now I will change all the even numbers in the data list \n"
"to negative numbers")
k = 0
for k in range(len(number_list)):
i = number_list[k]
if i % 2 == 0:
i = i * -1
number_list[k] = i
k = k + 1
else:
k = k + 1
print(number_list)
print("Here are the negative numbers in their own data list")
k = 0
negative_number_list = []
for k in range(len(number_list)):
i = number_list[k]
if i < 0:
negative_number_list.append(i)
k = k + 1
else:
k = k + 1
print(negative_number_list)
print("Here is a list of all of the numbers")
sum_list = []
k = 0
while k < len(number_list):
sum_list.append(number_list[k])
k += 1
a = 0
while a < len(negative_number_list):
sum_list.append(negative_number_list[a])
a += 1
print(sum_list)
help(sum_list) | false |
cf9e93785bfc81f9d26c666366a78c979a0ec166 | raymondng1893/Python-CodingBatExercises | /CodingBatString-1/extra_end.py | 292 | 4.28125 | 4 | # Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2.
def extra_end(str):
start = len(str) - 2
return 3*str[start:]
print(extra_end('Hello'))
print(extra_end('ab'))
print(extra_end('Hi'))
| true |
f8f2d3e0d9fb69a648c079cf5682afb0242eff54 | raymondng1893/Python-CodingBatExercises | /CodingBatString-2/count_hi.py | 266 | 4.25 | 4 | # Return the number of times that the string "hi" appears anywhere in the given string.
import re
def count_hi(str):
count = re.findall('hi', str)
return len(count)
print(count_hi('abc hi ho'))
print(count_hi('ABChi hi'))
print(count_hi('hihi'))
| true |
608aea8f1c2d4fd673d29ee20cadfeff30cdc245 | TarikEskiyurt/Python-Projects | /Determine Prime Number.py | 324 | 4.21875 | 4 | number=int(input("Please enter the number")) #I take a number from user
counter=0
for i in range(2,number):
if number%i==0:
counter=counter+1
if counter > 0:
print("It is not a prime number.") #I print output to screen
else:
print("Is the prime number.") #I print output to screen
| true |
4cf8466775023cd269a1959762ae2d87a9eda0e0 | imodin07/Python-Basics | /FileWritin.py | 797 | 4.125 | 4 | # Creating a new text file.
f = open("writee.txt", "w") # 'f' is file handle. 'w' is write mode.
f.write("It's a beautiful day out there. ") # With the help of 'f.write' we can write the file.
f.close() # Command to close file.
# Append Function in File writing
f = open("writee.txt", 'a') # here 'a' is used for appending the file.
f.write("\nIt's so hot in here.") # \n is new line character
f.close()
# Tip : In append the previous data in file is still there.
# How to find the number of character returned by append command.
f = open("writee.txt", 'a')
a = f.write("\nIt's so hot in here.") # Here a return number of charaters present in file.
print(a)
| true |
a642e37cd7f786b709a2186939ad0615fb4d0f16 | shuihan0555/100-days-of-python | /day014/main.py | 1,068 | 4.1875 | 4 | # coding=utf-8
"""Day 014 - setdefault: When dict.get it's a bad idea.
This example covers the difference between dict.get and dict.setdefault functions.
Setdefault is a function that is more efficient that dict.get,
because it already set a default value if the key doesn't exists
and return the value.
"""
def run():
netflix = { 'movies': ['Star Wars', 'The Martian', 'Interestelar'] }
# Nothing efficient way to non existent keys with dict.get
tv_shows = netflix.get('tv_shows', [])
tv_shows.append('How I Met Your Mother')
netflix['tv_shows'] = tv_shows
print(netflix)
# >>> {'movies': ['Star Wars', 'The Martian', 'Interestelar'], 'tv_shows': ['How I Met Your Mother']}
### Efficient way to non existent keys with dict.setdefault
netflix.setdefault('animes', []).append('Sakurasou no Pet na Kanojo')
print(netflix)
# >>> {'movies': ['Star Wars', 'The Martian', 'Interestelar'], 'tv_shows': ['How I Met Your Mother'], 'animes': ['Sakurasou no Pet na Kanojo']}
if __name__ == '__main__':
run()
| true |
6a2b485596a36d8ac8e35762ef3c79f3d3bcfab8 | shuihan0555/100-days-of-python | /day006/main.py | 1,084 | 4.1875 | 4 | # coding=utf-8
def run():
# Attributing tuple values in variables
name, age, height, weight = ('Marcos', 21, 173, 62)
print("Name: {} - Age: {} - Height: {} - Weight: {}".format(
name, age, height, weight)
)
# >>> Name: Marcos - Age: 21 - Height: 173 - Weight: 62
animes = (
('Attack on Titan', 'Seinen'),
('Sakurasou no Pet na Kanojo', 'Slice Of Life'),
('Fullmetal Alchemist', 'Shonen'),
)
for anime in animes:
# The operator '%' understand the tuple 'anime' as separated fields
print("%s/%s" % anime)
# >>> Attack on Titan/Seinen
# Sakurasou no Pet na Kanojo/Slice Of Life
# Fullmetal Alchemist/Shone
cities = ['Porto Alegre', 'Rio de Janeiro', 'Minas Gerais']
# Creating a tuple with Generator Expressions (genexp)
# Generator Expressions are used to create sequences like Tuple
cities_tuple = tuple(city for city in cities)
print(cities_tuple)
# >>> ('Porto Alegre', 'Rio de Janeiro', 'Minas Gerais')
if __name__ == '__main__':
run()
| false |
26a496a3ee887173f2ded8cfd166c9987f4ce210 | JonOlav95/algorithm_x | /backtracking/backtrack_helpers.py | 1,371 | 4.125 | 4 | from backtracking.backtrack_node import Node
def arr_to_node(arr):
node_arr = [[Node() for i in range(len(arr))] for j in range(len(arr[0]))]
for i in range(9):
for j in range(9):
node = Node()
node.x = j
node.y = i
if arr[i][j] != 0:
node.set_value(arr[i][j])
node_arr[i][j] = node
return node_arr
def node_to_arr(node_matrix):
"""Creates a matrix of integers from a matrix of Nodes.
Used after the backtracking algorithm is done to return a more common format
of the sudoku board.
Args:
node_matrix: A matrix of Nodes which represents the Sudoku board.
Returns:
sol: A matrix of integers which represents the Sudoku board.
"""
sol = []
for y in range(9):
row = []
for x in range(9):
row.append(node_matrix[y][x].value)
sol.append(row)
return sol
def print_board(node_matrix):
"""Prints the Sudoku board in the console.
Args:
node_matrix: A matrix of Nodes which represents the Sudoku board.
"""
for y in range(9):
for x in range(9):
node = node_matrix[y][x]
val = 0
if node.value != -1:
val = node.value
print(str(val) + " ", end="")
print("")
print("")
| true |
f37c99c9a7412bc00b5be50ef7e76e174c859575 | Swinvoy/Cyber_IntroProg_Group1 | /Quizes/Exceptions and Input Validation/getIpAddress.py | 882 | 4.25 | 4 | # Write a function called 'GetIpAddress' that will keep asking the user to enter an IP Address until it is valid. The function will then return the IP address as a string.
# 255.255.255.255
def getIpAddress():
noError = False
while noError == False:
try:
ipAddress = input("What IP Address do you want to check: ")
ipAddressList = ipAddress.split(".")
if len(ipAddressList) != 4:
raise ValueError
for x in range (0,4):
y = int(ipAddressList[x])
if y > 265 or y < 0:
raise ValueError
if ipAddressList[0] == "0":
raise ValueError
noError = True
print("That is a valid IP Address!")
return ipAddress
except:
print("That is not an IP Address!")
print(getIpAddress()) | true |
572bbb8d6a87bb282ad30707fce34dc7e9bfb12c | AShipkov/AShipkov-Python-Algorithms-and-Data-Structures | /lesson3_3.py | 891 | 4.15625 | 4 | """
3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
"""
import random
random_list = random.sample(range(0,1000), 5)
print(f'{"Массив случаных чисел":25} {random_list}')
index_max = index_min = 0
number_max = random_list[0]
number_min = random_list[0]
for index, number in enumerate(random_list):
if(number > number_max):
number_max = number
index_max = index
if(number < number_min):
number_min = number
index_min = index
random_list[index_min], random_list[index_max] = random_list[index_max], random_list[index_min]
print(f'{"Массив измененный":25} {random_list}\nЗамена местами максимального числа {number_max} и минимального числа {number_min}') | false |
ce6785e84216dff35bff5cfdf9236074a534d712 | AShipkov/AShipkov-Python-Algorithms-and-Data-Structures | /lesson3_7.py | 927 | 4.1875 | 4 | """
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба являться минимальными), так и различаться.
"""
import random
random_list = random.sample([i for i in range(0, 10)] * 2,10)
print(random_list)
numbers = {}
for index, number in enumerate(random_list):
if 'min_number1' not in numbers:
numbers['min_number1'] = number
elif number < numbers['min_number1']:
numbers['min_number2'] = numbers['min_number1']
numbers['min_number1'] = number
elif 'min_number2' not in numbers:
numbers['min_number2'] = number
elif number < numbers['min_number2']:
numbers['min_number2'] = number
print(f"Два наименьших числа {numbers['min_number1']} и {numbers['min_number2']}") | false |
6b970c0e14015da18e596f5c07aaa0c8e5cac8fc | xiao-miao97/xiao_learn | /练习191225.py | 1,256 | 4.125 | 4 | '''
华氏温度转换为摄氏温度
'''
f = float(input('请输入华氏温度:'))
c = (f - 32) /1.8
print('%.1f华氏温度 = %.1f摄氏温度' % (f, c))
'''
输入圆的半径计算周长和面积
'''
import math # math是常用数学函数库,math.pi是圆周率
r = float(input('请输入圆的半径: '))
z = r ** 2 * math.pi
y = 2 * math.pi * r
print('圆的周长为%.2f,面积为%.2f' % (y, z))
'''
math中常用数学函数
ceil(x) 取顶
floor(x) 取底
fabs(x) 取绝对值
factorial(x) 阶乘
hypot(x,y) sqrt(x*x+y*y)
pow(x,y) x的y次方
sqrt(x) 开平方
log(x)
log10(x)
trunc(x) 截断取整数部分
isnan (x) 判断是否NaN(not a number)
degree (x) 弧度转角度
radians(x) 角度转弧度
e = 2.718281828459045
pi 圆周率
'''
########################################################
'''
输入年份,闰年输出True,否则输出False
'''
year = int(input('请输入年份:'))
f = (year % 4 == 0 and year % 100 != 0) or \
year % 400 == 0
'''
"\"的作用:
1.后跟字符表示转义字符,如\n表示换行
2.续行,如果一行太长了想分行,在第一行后加空格\,就可以把剩下的写到第二行。
'''
print(f) | false |
e7a3547585379afed4381762a14e51ffc7400400 | tamsynsteed/palindrometask | /recursiontask.py | 616 | 4.3125 | 4 | #if the string is made of no letters or just one letter, then it is a palindrome.
def palindrome(s):
if len(s) < 1:
return True
#check if first and last letters are the same
else:
if s[0] == s[-1]:
# if the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. This function checks the middle, substring.
return palindrome(s[1:-1])
else:
return False
a=input("Enter string:")
if(palindrome(a)==True):
print("String is a palindrome!")
else:
print("String isn't a palindrome!")
| true |
f4b5aa25d217a23e345e7c0b5ad1479941c5d78d | chennakesava1/python | /con.py | 1,316 | 4.1875 | 4 | #!/user/bin/python
inputs = float(input("enter ur number"))
if inputs == 3:
print ("con is truu")
else:
print "input is not 3"
##elif
inputs = float(input("enter the second number"))
if inputs == 2:
print "given number is 2"
elif inputs > 2:
print "given number below 2"
else:
print "given number abow 2"
##Nested if
inputs = float(input("enter the 3rd number"))
if inputs <= 4:
if inputs == 4:
print "Given number is 4"
else:
print "given number below 4"
else:
print "given number not in 0 to 4"
friends = raw_input("type a first later of ur friend name")
if friends == 'm':
print ("Mounika")
elif friends == 'p':
print ("Praveen")
elif friends == 'r':
print ("rama rao")
elif friends == 'k':
print ("Koti")
else:
print (" your friends list need to update ")
print "Thank you !"
a = int(input("enter a: "))
b = int(input("enter b: "))
c = int(input("enter c: "))
if a < b < c:
print ( "given numbers a < b < c")
else:
print ( " given numbers are not like a<b<c")
ab = int(input("enter a number only: "))
cd = int(input("enter a number morethen ab"))
if ab < cd:
print("ab < cd")
else:
print("ab > cd ")
if ab < 10 and ab > 5:
print ( " ab value in betwin 5 to 10")
else:
print (" ab value not inbetwin 5 to 10")
| false |
1daca47cdf2cd8d0feb87b65d4d17f19410a01e8 | acikgozmehmet/Python | /TicTacToe/TicTacToeStudent.py | 2,395 | 4.34375 | 4 | ## @author Mehmet ACIKGOZ
# This program simulates a simple game of Tic-Tac-Toe
def main():
MAX_TURNS = 9
turnsTaken = 0
isWinner = False
board = createBoard()
player = "O"
while (not isWinner and turnsTaken < MAX_TURNS) :
# Switch players
# (If player contained an O assign an "X", else assign an "O")
if (player == 'O'):
player = 'X'
elif (player == 'X'):
player = 'O'
# Show the board (Call the showBoard function)
showBoard(board)
# Prompt for and retrieve the row and column for the player
# (Be sure to match the output)
print("\nPlayer %s's turn " % player)
r = int(input("Row: "))
c = int(input("Col: "))
# Place the X or O on the board (Hint: use the value of player)
board[r][c] = player
# Increment # of turns and check for win (completed)
turnsTaken = turnsTaken + 1
isWinner = checkWin(board, player)
# Game is now over, so show the final board (Call showBoard function)
showBoard(board)
# Display who won or if it was a cat. (Match the output)
if turnsTaken == MAX_TURNS:
print("Cat!")
else:
print("%s wins!" % player)
# showBoard shows a tic tac toe board in a table format
# @param board The tic tac toe board
def showBoard(matrix):
for i in range(3):
for j in range(3):
print(matrix[i][j], end = " ")
print()
# createBoard creates a 3x3 tic-tac-toe board
# where each element is a dash
# @return the created board
def createBoard():
A = []
for i in range(3):
row = ['-']*3
A.append(row)
return A
# checkWin determines if a win occurred in a row, column, or diagonal
# @param board The Tic-Tac-Toe board
# @param player Contains an "X" or "O" representing a player
# @return True or False depending if the game is won
def checkWin(board,player):
for i in range(3):
if (player == board[i][0] == board[i][1] == board[i][2]):
return True
if (player == board[0][i] == board[1][i] == board[2][i]):
return True
if (player == board[0][0] == board[1][1] == board[2][2]) :
return True
if(player == board[2][0] == board[1][1] == board[0][2]):
return True
main() | true |
fb23d64f4c9943f1f81aae0f41d9e253d183e843 | Ryuuken-dev/Python-Zadania | /Moduł VII-lekcja 41/41_1.py | 1,483 | 4.34375 | 4 | """
Przygotuj mini program do zarządzania Twoimi oszczędnościami. Starasz się wpłacać pieniądze
z różnych źródeł, chcesz na bieżąco wiedzieć, ile udało Ci się już zaoszczędzić.
"""
from datetime import datetime
class Saving:
def __init__(self, date: datetime, saving_value: float):
self._saving_value = saving_value
self._date = date
@property
def saving(self):
return self._saving_value
@saving.setter
def saving(self, value):
if value > 0:
self._saving_value += value
@property
def get_date(self):
return self._date
@get_date.setter
def get_date(self, date):
self._date = date
class Savings:
def __init__(self):
self.savings = []
def add_saving(self, saving: Saving):
self.savings.append(saving)
@property
def collection(self):
total = ''
for item in self.savings:
total += f'Oszczędności: {item.saving}\tData: {item.get_date}\n'
return total
@property
def total(self):
summary = 0
for item in self.savings:
summary += item.saving
return f'Razem: {summary}'
saving = Saving(datetime(2021, 4, 12), 120.64)
saving_2 = Saving(datetime(2021, 5, 12), 1200.64)
saving.saving = 1200
saving.get_date = datetime(2021, 5, 13)
savings = Savings()
savings.add_saving(saving)
savings.add_saving(saving_2)
print(savings.collection)
print(savings.total) | false |
6a4f626b7137370d353e7f335d38688a616b5610 | Ryuuken-dev/Python-Zadania | /Moduł II-praca domowa/HowManyChars.py | 315 | 4.1875 | 4 | # Napisz program zliczający ilość wystąpień każdego znaku w zadanym napisie
users_word = input('Podaj zdanie: ')
how_many_chars = {}
for word in users_word:
if word not in how_many_chars:
how_many_chars[word] = users_word.count(word)
print(f'Znak: {word} Ilość: {how_many_chars[word]}')
| false |
cc5dcbdcdaa89a3e66d23e9e0ba40369e47c62e5 | Ryuuken-dev/Python-Zadania | /Moduł VI-lekcja 36/36_2.py | 1,100 | 4.125 | 4 | """
Przygotuj klasę Car, która powinna przechowywać nazwę samochodu oraz jego cenę
i maksymalną prędkość. Zapytaj użytkownika o 5 samochodów, a następnie wypisz je na ekranie w
kolejności od najdroższego do najtańszego oraz poniżej od najwolniejszej do najszybszej
prędkości.
"""
class Car:
def __init__(self, car_name: str, car_price: int, max_speed: int):
self.car_name = car_name
self.car_price = car_price
self.max_speed = max_speed
self.data = [self.car_name, self.car_price, self.max_speed]
def add_data(self):
return self.data
cars = []
for num in range(1, 6):
users_car_name = input('Podaj markę samochodu: ')
users_car_price = int(input('Podaj cenę samochodu: '))
users_car_speed = int(input('Podaj prędkość maksymalną samochodu: '))
users_car = Car(users_car_name, users_car_price, users_car_speed)
cars.append(users_car.add_data())
from_dearest = list(reversed(sorted(cars, key=lambda car: car[1])))
from_slower = sorted(cars, key=lambda car: car[2])
print(from_dearest)
print(from_slower)
| false |
e59e17fabd7f5c6677ce7b90f2735be699f1132b | Ryuuken-dev/Python-Zadania | /Practice Python/List Less Than Ten.py | 740 | 4.34375 | 4 | """
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
1. Instead of printing the elements one by one, make a new list that has all the elements
less than 5 from this list in it and print out this new list.
2. Write this in one line of Python.
3. Ask the user for a number and return a list that contains only elements
from the original list a that are smaller than that number given by the user.
"""
users_num = int(input('Podaj liczbę: '))
item_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print(f'{[item for item in item_list if item < users_num]}')
print(f'{[item for item in item_list if item < 5]}') | true |
7b0e0ad002ed665d5ec79acafa59ae783b6dae56 | Ryuuken-dev/Python-Zadania | /Moduł II-lekcja 12/12.1.py | 1,186 | 4.25 | 4 | """
Przygotuj mały słownik języka angielskiego, pytaj użytkownika co chce zrobić i wyświetlaj mu słowo
przetłumaczone na język polski lub na język angielski.
"""
users_choice = input('Podaj parę językową-Polski>Angielski (P>A), Angielski>Polski (A>P): ').lower()
users_choice = users_choice.replace(' ', '')
words = {
'chomik': 'hamster',
'papuga': 'parrot',
'dzięcioł': 'woodpecker',
'wieloryb': 'whale',
'gepard': 'cheetah',
}
users_word = input('Podaj słowo: ').lower()
def check_pol_word():
for word in words:
if word == users_word:
print(f'{word.upper()} po polsku to {words[word].upper()} po angielsku.')
elif users_word not in words:
print('Nie mamy takiego słowa w bazie danych!')
quit()
def check_ang_word():
for word in words:
if users_word == words[word]:
print(f'{words[word].upper()} po angielsku to {word.upper()} po polsku.')
elif users_word not in words.values():
print('Nie mamy takiego słowa w bazie danych!')
quit()
if users_choice == 'p>a':
check_pol_word()
elif users_choice == 'a>p':
check_ang_word()
| false |
822f149e5cc3c35b5fd057c38b45de473d2c950a | BhujayKumarBhatta/OOPLearning | /pOOP/pOOp/static_method.py | 1,516 | 4.21875 | 4 | '''
Created on 02-Oct-2018
@author: Bhujay K Bhatta
'''
'''
Static methods are a special case of methods.
Sometimes, you'll write code that belongs to
a class, but that doesn't use the object itself at all.
For example:
'''
class Pizza(object):
@staticmethod
def mix_ingradients(x, y):
return x + y
# Static method without self means not dependent
# the state of the object
def cook(self):
return self.mix_ingradients(self.cheese, self.vegetables)
'''
In such a case, writing mix_ingredients as a non-static method would work too,
but it would provide it with a self argument that would not be used. Here,
the decorator @staticmethod buys us several things:
Python doesn't have to instantiate a bound-method for each Pizza
object we instantiate. Bound methods are objects too,
and creating them has a cost. Having a static method avoids that:
>>> Pizza().cook is Pizza().cook
False
>>> Pizza().mix_ingredients is Pizza.mix_ingredients
True
>>> Pizza().mix_ingredients is Pizza().mix_ingredients
True
It eases the readability of the code: seeing @staticmethod
, we know that the method does not depend on the state of the object itself;
It allows us to override the mix_ingredients method in a subclass.
If we used a function mix_ingredients defined at the top-level of our module,
a class inheriting from Pizza wouldn't be able to change the way we mix
ingredients
for our pizza without overriding cook itself.
'''
| true |
78c733bb240940129d830fefe817a8bd1d7ac956 | KrishnaSindhur/python-scripts | /cp/stack.py | 1,491 | 4.40625 | 4 | # dynamic stack operation
class Stack(object):
def __init__(self, limit=10):
self.stk = limit*[]
self.limit = limit
def is_empty(self):
return self.stk <= 0
def push(self, item):
if len(self.stk) >= self.limit:
print("stack is full")
print("stack is resize")
self.resize()
else:
self.stk.append(item)
print("The pushed element to stack is %s" % self.stk[-1])
def peek(self):
if len(self.stk) <= 0:
print("stack is underflow")
else:
print("The top most element in current stack is %s" % self.stk[-1])
def size(self):
print("The length of the stack is %s" % len(self.stk))
def pop(self):
if len(self.stk) <= 0:
print("stack underflow")
return 0
else:
print("The deleted element from stack is %s" % self.stk.pop())
def resize(self):
newstk = list(self.stk)
self.limit = 2*self.limit
self.stk = newstk
our_stack = Stack()
our_stack.push('3')
our_stack.push('3')
our_stack.push('4')
our_stack.push('5')
our_stack.push('6')
our_stack.size()
our_stack.peek()
our_stack.push('7')
our_stack.push('8')
our_stack.push('9')
our_stack.push('10')
our_stack.push('11')
our_stack.push('1')
our_stack.pop()
our_stack.pop()
our_stack.peek()
our_stack.size()
'''stack is one of the popular data structures
this is one of the way to implement'''
| true |
6f8efad9b8fb1792c14a4af94707d6a9f1cb3d3a | Noorul834/PIAIC | /assignment03.py | 669 | 4.125 | 4 | # 3. Divisibility Check of two numbers
# Write a Python program to check whether a number is completely divisible by another number. Accept two integer values form the user
# Program Console Sample Output 1:
# Enter numerator: 4
# Enter Denominator: 2
# Number 4 is Completely divisible by 2
# Program Console Sample Output 2:
# Enter numerator: 7
# Enter Denominator: 4
# Number 7 is not Completely divisible by 4
num1=int(input("Enter the numerator: "))
num2=int(input("Enter the denominator: "))
if num1%num2==0:
print(f"number {num1} is completely divisible by {num2}.")
else:
print(f"number {num1} is not completely divisible by {num2}.") | true |
79e9aabb9a44898766e4c9fd5af2edefd0f86304 | Jordan-1234/Wave-1 | /Volume of a Cylinder.py | 265 | 4.28125 | 4 | import math
radius = float(input("Enter in the radius of the cylinder "))
height = float(input("Enter in the height of the cylinder "))
cylinder_Area = (2 * math.pi * pow(radius,2) * height)
print('The volume of the cylinder will be ' + str(round(cylinder_Area,1))) | true |
373a821293faaec8b08aa36dd08a9f3753b5e3d6 | lilymaechling/codingAssignment4 | /helper.py | 1,971 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Helper File Created on Mon Mar 23 22:25:37 2020
@author: deepc
"""
# In this "alive" code below, we will provide many subroutines (functions) in Python 3 which may be useful.
# We will often provide tips as well
import matplotlib.pyplot as plt
def read_pi(n):
#opens the file name "pi" and reads the first n digits
#puts it in the list pi, and returns that list
pi = list()
f = open('pi','r')
for i in range(n):
d = f.read(1)
pi.append(int(d))
return pi
def graph_plot(n):
# needs matplotlib.pyplot
# X-axis: numbers 1 to n
# Y-axis: i^2 for i in range 1 to n
X = list()
Y = list()
for i in range(1,n):
X.append(i)
Y.append(i*i)
plt.plot(X,Y)
plt.show()
#Please feel free to google matplotlib and find how to modify its various features.
def convert_int_to_list(N):
#takes a number N and makes a list with its single digits
#Example: it takes 1729 and forms [1,7,2,9]
L = list()
s = str(N) #make N into a string
for i in s:
L.append(int(i))
return L
#The above can be succinctly written as "return [int(i) for i in str(N)]"
#That would be much faster
def convert_list_to_int(L):
#Takes a list of single digit integers and makes it into one single integer read left to write
#Again, it makes a string concatenating the whole list
#and then uses the int() function
s = ""
for i in L:
s = s + str(i)
return int(s)
def read_countries():
#opens the file named "country.txt"
#returns a list of all countries which are 7 letters or more (counting spaces)
#all lower case
countries = list()
with open("countries.txt") as file:
for line in file:
line = line.strip() #or some other preprocessing
if(len(line) > 6):
c = line.lower()
countries.append(c)
return countries
| true |
d183aa5bbc14b2ec779224ae2ce86ca0be3547b4 | ghostvic/leetcode | /RotateArray.py | 1,151 | 4.25 | 4 | '''
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
'''
'''
The idea of this solution is: the array we can cut it into 3, A:[1,2,3,4] B:[5,6,7].
To get the result[B,A], first revers A, then reverse B, then reverse the entire array.
The time complexity is O(n) and space complexity is O(1)
'''
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {void} Do not return anything, modify nums in-place instead.
def rotate(self, nums, k):
length = len(nums)
if k == 0 or k == length:
return
if k < 0:
return None
if k > length:
k = k % length
self.reverse(nums, 0, length - 1 - k)
self.reverse(nums, length - k, length - 1)
self.reverse(nums, 0, length - 1)
def reverse(self, myList, start, end):
tmp = 0
while start < end:
tmp = myList[start]
myList[start] = myList[end]
myList[end] = tmp
start += 1
end -= 1
| true |
28c4806baade080629c649028bd8b36e12dd7de4 | SoenMC/Programacion | /EjercicioFun8_men_may.py | 1,068 | 4.46875 | 4 | '''
Confeccionar una función que reciba tres enteros y los muestre ordenados de menor a mayor.
En otra función solicitar la carga de 3 enteros por teclado
y proceder a llamar a la primer función definida.
'''
def ordenar_enteros(num1,num2,num3):
if num1<num2 and num1<num3:
print(num1)
if num2<num3:
print(num2)
print(num3)
else:
print(num3)
print(num2)
elif num2<num1 and num2<num3:
print(num2)
if num1<num3:
print(num1)
print(num3)
else:
print(num3)
print(num1)
elif num3<num1 and num3<num2:
print(num3)
if num1<num2:
print(num1)
print(num2)
else:
print(num2)
print(num1)
def cargar_numeros():
num1=int(input("Primer numero -> "))
num2=int(input("Segundo numero -> "))
num3=int(input("Tercer numero -> "))
ordenar_enteros(num1,num2,num3)
cargar_numeros() | false |
bb98c4b3f474ea603a9576dd81713e0af8d3bf70 | Ezdkdr/Algorithms | /RainTrap.py | 967 | 4.25 | 4 | # a function that takes a list of positive integers as argument. The elements represent the lengths of the towers
# it returns the number of units of water trapped between the towers
#from typing import List, Any
def measure_trapped_water(arr):
i = 0
trapped_water_units = 0
j = len(arr) - 1
added = True
while added:
while i < j and arr[i] == 0:
i += 1
while i < j and arr[j] == 0:
j -= 1
water_units = j - i + 1
for k in range(i, j + 1):
if arr[k] > 0:
water_units -= 1
arr[k] -= 1
if water_units <= 0 or i == j:
added = False
else:
trapped_water_units += water_units
return trapped_water_units
l = list(input("input the list of items (comma separated): ")) # type: List[Any] # example: 0,1,0,0,2,0,4,0,3,0,0,2,1,0,3,0
print ("The quantity of trapped water units is :", measure_trapped_water(l))
| true |
6b9fda45cb8bbc08d20afba5d0919d2dd2f9e15c | dcgibbons/learning | /advent_of_code/2019/day10.py | 1,988 | 4.25 | 4 | #!/usr/bin/env python3
#
# day10.py
# Advent of code 2019 - Day 10
# https://adventofcode.com/2019/day/10
#
# Chad Gibbons
# December 20, 2019
#
import math
import sys
def read_map(filename):
# reads a map from an input file - assuming one row per line of text
map = []
with open(filename) as fp:
line = fp.readline()
while line:
map.append(line.rstrip()) # remove trailing newlines
line = fp.readline()
return map
def find_asteroids(map):
# look at the entire map and extract a list of asteroids to simply
# further processing
n = len(map[0])
asteroids = list()
for x in range(0, n):
for y in range(0, n):
if map[y][x] == '#':
asteroids.append((x,y))
return asteroids
def find_max_visible_asteroids(map):
# compute the slope between every asteroid and every other asteroid - any
# asteroids that share the same slope between another asteroid will only be
# counted as visible once, since the other asteroid obscures it
best = 0
for a in asteroids:
slopes = set()
for b in asteroids:
if a == b: continue # skip ourselves
# slope here is defined as the X and Y distance between each other,
# and then that fraction reduced so that the entire map is
# normalized
slope = (b[1]-a[1], b[0]-a[0])
gcd = math.gcd(slope[0], slope[1])
slope = (slope[0]/gcd,slope[1]/gcd)
slopes.add(slope)
# the total number of unique slopes is how many asteroids this asteroid
# can see; keep track of the highest number so far
if len(slopes) > best:
best = len(slopes)
print("best asteroid is %r with %d asteroids visible" % (a, best))
return best
if __name__ == '__main__':
map = read_map(sys.argv[1])
asteroids = find_asteroids(map)
best = find_max_visible_asteroids(map)
print(best)
| true |
34d5fc23e16c4eb8acca98dd368726b427f09b0f | ahhampto/py4e | /ex_7.2.py | 1,108 | 4.125 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
#X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.
#Do not use the sum() function or a variable named sum in your solution.
#You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
try:
fhand = open(fname)
except:
print("File cannot be opened:",fname)
exit()
count = 0
average = 0
for line in fhand:
if not line.startswith("X-DSPAM-Confidence:"): continue
pos = line.find(" ")
#originally missing
val = line[pos:].rstrip()
#originally missing
fval = float(val)
#originally not included under for loop
count = count + 1
average = average + fval
print("Average spam confidence:", average/count)
| true |
3a833c388abc1fd1e27c14a603e3780b8b6fd657 | Asmin75/Beeflux_soln | /2.py | 235 | 4.125 | 4 | """Q2.
Consider a dictionary
d = {1:1, 2:2, 3:3}
a. whats the value of d[4] ??
b. How can you set 9 value in 2 key.
Write a program to print value with 2 key."""
d = {1:1, 2:2, 3:3}
#print(d[4]) #give KeyError: 4
d[2]=9
print(d[2])
| true |
836b1abfb6f7ba743da277f73799926daf67aad6 | Asmin75/Beeflux_soln | /1.py | 386 | 4.21875 | 4 | """Q1.
Create a function to sum Input Numbers (parameters) which returns sum of inputed numbers. Also write Unittest for the function.
my_sum(1,2) should return 3 e.g.
my_sum(1,2,3) should return 6
my_sum(1,3,5,7,8) = ?"""
def my_sum(*args):
total = 0
for num in args:
total += num
return total
def unittest():
print(my_sum(1, 3, 5, 7, 8))
unittest() | true |
5a811e8625601ba78a4723e4a92539f15573376d | wangjiaqiys/tensorflow2.0 | / Data_Structures_Algorithms/_deque.py | 934 | 4.125 | 4 | # _*_ coding:utf-8 _*_
"""
双端队列(deque, double-ended queue): 是一种具有队列和栈的性质的数据结构
单独看双端队列的一端, 相当于一个栈, 相当于两个栈底合在一起
"""
class Deque():
def __init__(self):
self.__list = []
def add_front(self, item):
"""从对头加入一个item元素"""
self.__list.insert(0, item)
def add_rear(self, item):
"""从队尾加入一个item元素"""
self.__list.append(item)
def remove_front(self):
"""从队头删除一个item元素"""
self.__list.pop(0)
def remove_rear(self):
"""从队尾删除一个item元素"""
self.__list.pop()
def is_empty(self):
"""判断双端队列是否为空"""
return self.__list == []
def size(self):
"""返回队列的大小"""
return len(self.__list)
if __name__ == "__main__":
s = Deque() | false |
a8448f10e865e57443ffddea639346d62ed63b15 | brealxbrealx/beetroot | /Homework5/h5task2.py | 712 | 4.375 | 4 | # Author: Andrey Maiboroda
# brealxbrealx@gmail.com
# Homework5
# task2
# this program Generate 2 lists with the length of 10 with random integers from 1 to 10, \
# and make a third list containing the common integers between the 2 initial lists without any duplicates.
import random
# generate 2 lists in range 10 with 10 index
list_first = random.choices(range(10), k=10)
list_second = random.choices(range(10), k=10)
# print 2 lists
print('First list',(list_first))
print('Second list',(list_second))
# declare third list which store common int between 2 lists
list_third = list(set(list_first)&set(list_second))
list_third.sort()
print('The common integers between the 2 initial lists without any duplicates is',(list_third)) | true |
2137e9ea6a4349220acb56ee37f258e245d479a8 | brealxbrealx/beetroot | /Homework8/h8task1.py | 481 | 4.28125 | 4 | # Author: Andrey Maiboroda
# brealxbrealx@gmail.com
# Homework8
# task1
# Write a function called oops that explicitly raises an IndexError \
# exception when called. Then write another function that calls oops inside a try/except statement to catch the error. What happens if\
# you change oops to raise KeyError instead of IndexError?
def oops():
raise IndexError
def oops_inside():
try:
oops()
except Exception:
print('Exception!!!!')
oops_inside()
| true |
98f9f3ab231065992f45e0b2a41ecb2904bfd1ef | Diegofergamboa/day-3-1-exercise | /main.py | 468 | 4.4375 | 4 | # 🚨 Don't change the code below 👇
number = int(input("Which number do you want to check? "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
if number % 2 == 1:
print('The number is odd')
else:
print('The number is even')
#It´s important to know that the modulo gives 0 when the number is even and 1 when the number is odd
#So, another way to code this challenge is:
if number % 2 == 0:
print('Even')
else:
print('Odd')
| true |
e3c90bb28c3d9df47a7eba8eb2ce678600bf4379 | OperationFman/LeetCode | /RevisionKit/Bubble-Sort.py | 677 | 4.21875 | 4 | # Given an array of integers, sort the array in ascending order using the Bubble
# Print the following three lines:
# Array is sorted in X swaps.
# First Element: Y
# Last Element: Z
# Where X, Y, Z are numbers
def countSwaps(a):
""" [2, 1, 3] """
# Clue: Follow the traditional method of bubble sort and run a counter for each swap.
count = 0
for i in range(len(a) - 1):
for x in range(len(a) - i - 1):
if a[x] > a[x + 1]:
a[x], a[x + 1] = a[x + 1], a[x]
count += 1
print("Array is sorted in " + str(count) + " swaps")
print("First Element: " + str(a[0]))
print("Last Element: " + str(a[-1]))
countSwaps([1,2,3,5,4,6,1,7,2]) | true |
da348de88096524bb92353cf5cd1a8c76947842a | Kuroposha/Data-itmo | /lesson05/lesson5.py | 2,796 | 4.3125 | 4 | """
Лекция 5. Модули, пакеты, дистрибуция пакетов(распространение)
Модуль - это обычный файл-Python
Названия для модуля имеют теже ограничения, что и остальные в пай
Регистр!
- Исполняемый (запускаемый / главный) модуль также называется MAIN
"""
#-- КАк импортировать модуль? --
#1. Испортировать целиком ( весь сразу)
#inpost mod.submod,subsu вариант импорта
# submod.fun
import sq_shapes
#имп. одно имя. точка - доступ к именам в модуле, и лать имя этой фукци
# 2. Частичный импорт
from sq_shapes import calculata_triangle_area, calculata_circle_area
# импортируем только нужные нам имена.. в режиме рид онли
print(sq_shapes.calculata_triangle_area(3, 6, 12))
print(sq_shapes.calculata_square_area(5))
# 3. Импорт из модуля всех имен в текущий модуль
from sq_shapes import *
__all__ = (
'calculata_circle_area',
'calculata_square_area',
'calculata_triangle_area',
'calculata_rectangle_area'
)
# Звездочка - это плохо, но это позволять залить все, что есть
# можно прописать
# Константы формиркодом, у н коф\нфликт по делам
#print(sq_shapes.debug.defg)error
sq_shapes.debug = True
print(genus)
print(sq_shapes.debug)
# вывод переменной окружения
#наш проект - python.path -sys.path линия поиска метода
# область видимости модуля - в модуле могут быть глоб пре, а в проге будут лок.
# можно юзать одинаковые имена в разных модулях
"""
Плюсы модулей:
1) модули компилируются пайтоном .pyc
2) для ускорения проги лучше убирать все лишнее из мейн. пай (некомп файлы)
3) pyc' и можно отдать вместо исх кода
4) в момент вызова интерпритатора мы можем передать ему нек доп аргументы
-O оптимизированные пик файлы
-OO убирает все комментарии, и оптимизирует код
5) он загружается только один раз (импортируется), но это можно фиксить
6) Пай может искать модули в тек дир и ниже, но не выше
"""
| false |
986bb3f771eaf065f792427508a7a33bc4d3a3ee | themanoftalent/Python-3-Training | /guessWrongNUmber.py | 449 | 4.25 | 4 | num = 0
secretnumber = 3
while True:
try:
num = int(input("Enter an integer 1-5: "))
except ValueError:
print("Please enter a valid integer 1-5")
continue
if num >= 1 and num <= 5:
break
else:
print('The integer must be in the range 1-5')
if num == secretnumber:
print('You won! the guess is {0}'.format(secretnumber))
else:
print(f'Wrong, you failed. The number entered is: {num}')
| true |
b250352075bd8f0c8ce67731bd9acea04b8756d2 | DanielOjo/variables | /Task 6.2.py | 402 | 4.28125 | 4 | #Daniel Ogunlana
#9/9/2014
#Task 6
#1.Write a program that will ask the user for three integers and display the total.
#2.Write a program that will ask the user for two integers and display the result of multiplying them together.
#3.Ask the user for the length, width and depth of a rectangular swimming pool. Calculate the volume of water required
#python Task 6.2
print ("What is 3 + 4 * 2?")
| true |
1c9c3138bcb59f06b7db6158e04fa706e5df5a52 | VitaliiStorozh/Python_Core | /HW3/3.4.py | 310 | 4.15625 | 4 | area = float(input("Hall's area(S) is: "))
radius = float(input("Stage's radius(R) is: "))
aisle = float(input("Aisle width(K) is: "))
from math import sqrt
if aisle*2 <= (sqrt(area) - (2*radius) ) :
print("The stage can be located in this hall")
else :
print("You should find another stage or hall")
| true |
f04698861002ec8c9db241672b00cee8f9834942 | VitaliiStorozh/Python_Core | /HW4/4.3(from_book).py | 1,099 | 4.15625 | 4 | my_bd = int(input('Year of your burn: '))
years_list = [my_bd, my_bd+1, my_bd+2, my_bd+3, my_bd+4, my_bd+5]
my_3th_bd = years_list[3]
print('Year when I was 3 year old:', my_3th_bd)
things = ["mozzarella", "cinderella", "salmonella"]
print('List of sth: ', things)
things[1] = "Cinderella"
print ('List with element connect wit people upper first letter:', things)
things[0] = "MOZZARELLA"
print('Next step: Chesse element in list upper letter: ', things)
del things[2]
things.append('Nobel prize')
print('Next step: Delete desease, get Nobel prize: ', things)
#Создайте список, который называется surprise и содержит элементы 'Groucho','Chico' и 'Harpo'.
surprise = ['Groucho', 'Chico', 'Harpo']
print(surprise)
#Напишите последний элемент списка surprise со строчной буквы, затем обратите его и напишите с прописной буквы.
str1 = str(surprise[2])
str1 = str1.lower()
surprise[2] = str1
print(surprise)
str1 = str1.title()
surprise[2] = str1
print(surprise)
9**9
| false |
23fc1a4b24c6bffe7676ae4fde1d37bee3274404 | sakiii999/Python-and-Deep-Learning-Lab | /Python Lab Assignment 2/Source/LA2_4.py | 417 | 4.15625 | 4 | import numpy as np
#Creates a list of array wit size 15 and range in between 0 to 20
random = np.random.randint(low=0,high=20,size=15)
print("The random vector is",random)
#Total count of each integer are calculated using bincount method
totalcount = np.bincount(random)
#Most occurences of an integer i.e. highest count is returned using argmax method
print("Most frequent item in the list is",np.argmax(totalcount)) | true |
8aca065e622cba0a79ce5d6b7332f57783ee15d1 | anujpanchal57/Udemy-Challenges | /Lect-43-challenge.py | 716 | 4.4375 | 4 | # Create a list of items (you may use either strings or numbers in the list),
# then create an iterator using the iter() function.
#
# Use a for loop to loop "n" times, where n is the number of items in your list.
# Each time round the loop, use next() on your list to print the next item.
#
# hint: use the len() function rather than counting the number of items in the list.
sample = ["Anuj", "Nidhi", "Radhika", "Viraj", "Aditi"]
# Iterator for above list
ravan_iterator = iter(sample)
# Loops for the number of times - 1 as and when compared with the list of items in SAMPLE
for char in range(0, len(sample)):
# Prints the next item every time the loop runs
print(next(ravan_iterator)) | true |
62f5189ad9440541eb7aeeb16b4ddcfa3ae944b2 | Psp29/basic-python | /chapter 4/03_list_methods.py | 572 | 4.25 | 4 | # Always use the python docs to find all the info!!
list1 = [1, 5, 3, 7, 86, 420, 69]
print(list1)
# list1.sort() # sorts the list
# list1.reverse() # reverses the list
# list1.append(669) # adds the elements at the end of the list.
# list1.insert(3, 5) # Inserts the element at the specific position here, first value is the index where we will be adding the value and second is the value itself.
# list1.pop(3) # it will delete the element at the 3rd index
# list1.remove(86) # it will remove the specified value and no need to specify the index
print(list1)
| true |
28b8d144e32d73af5edd0c5247354c3b65e3d691 | Psp29/basic-python | /speedlearn.py | 521 | 4.125 | 4 | # (tuples are immutable means that we cannot replace the values in an tuples) and are denoted by brackets i.e. ()
# e.g. x = (3, 'string', 4.0)
# list (it is mutable means they store reference of the items not the copy, basically you can change, append, add, remove items in a list) are denoted by square brackets []
# e.g. x = [4, 'Lassan', 3.5]
x = input("What is your name: ")
if x == 'Boris':
print('Privyet, ' + x + '!!')
elif x == 'Vadim':
print(x + ' Blyaat!!')
else:
print('Hello, ' + x + '!!!')
| true |
789afdfbbf8c0dec19bb5fb2e2ccfc121b058886 | Psp29/basic-python | /chapter 6/01_conditionals.py | 467 | 4.15625 | 4 | a = input("Enter value of a: ")
b = input("Enter value of b: ")
# if-elif-else ladder
# if(a > b):
# print("The value of a is greater than b.")
# elif(a == b):
# print("value a is equal to b.")
# else:
# print("The value of b is greater than a.")
# Multiple if statements
if(a > b):
print("The value of a is greater than b.")
if(a == b):
print("value a is equal to b.")
if(b > a):
print("The value of b is greater than a.")
print("Done.")
| true |
0bf4818daf53695a7a026b679abcafc2980ee80d | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex04.py | 545 | 4.21875 | 4 | #Exercício Python 004: Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
frase = input('Digite algo:')
print('O tipo primitivo desse valo é:',type(frase))
print('Só tem espaços?', frase.isspace())
print('É um número?', frase.isalnumeric())
print('É alfabético?', frase.isalpha())
print('É alfanumérica?', frase.isalnum())
print('Está em maiusculo?', frase.upper())
print('Está em minusculo?', frase.lower())
print('Está Capitalizada?', frase.title()) | false |
e2933d6c61d51c209647c89f7b1a53828383e644 | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex42.py | 717 | 4.125 | 4 | # Exercício Python 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# - EQUILÁTERO: todos os lados iguais
# - ISÓSCELES: dois lados iguais, um diferente
# - ESCALENO: todos os lados diferentes
r1 = float(input('Primeiro segmento:'))
r2 = float(input('Segundo segmento:'))
r3 = float(input('Terceiro segmento:'))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print('É possível formar um triângulo!')
if r1 == r2 == r3:
print('Tipo:EQUILÁTERO')
elif r1 == r2 or r2 == r3 or r1 == r3:
print('Tipo:ISÓSCELES')
else:
print('Tipo:ESCALENO')
else:
print('Não é possível formar um triângulo!') | false |
3c62d8f25c65cebdcb2f90b600bc44c11fd2c4e0 | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex28.py | 807 | 4.46875 | 4 | # Exercício Python 028: Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.O programa deverá escrever na tela se o usuário venceu ou perdeu.
#Importei a biblioteca Random e a função randint que randomiza um número inteiro que aí foi de 1 a 5
from random import randint
#Aqui criei um variavel computador para armazenar o randint
computador = randint(1,6)
print('''
Vamos jogar um jogo?
Tente acertar um número que eu pensei
Vamos lá
''')
jogador = int(input('Seu palpite:'))
#Se o número do computador for igual ao meu palpite eu ganho, se não, eu perco
if computador == jogador:
print('Parabéns, Você acertou!')
else:
print('Que pena, você não conseguiu!') | false |
670ee009fae5d0614817e49e7396e17b21ed2a3f | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex26.py | 471 | 4.125 | 4 | # Exercício Python 026: Faça um programa que leia uma frase pelo teclado e
# mostre quantas vezes aparece a letra "A",
# em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
f = str(input('Digite uma frase: ')).strip().upper()
print('A letra "A" aparece {} vezes nessa frase'.format(f.count('A')))
print('A mesma letra aparece pela primeira vez na posição {}'
' e pela última na {}'.format(f.find('A')+1,f.rfind('A')+1))
| false |
8a5c4b17873dfdf37705f91b8c27ea4e774ed86c | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex37.py | 627 | 4.1875 | 4 | # Exercício Python 037: Escreva um programa em Python que leia
#um número inteiro qualquer e peça para o usuário escolher
#qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal.
num = int(input('Digite um número:'))
print('''
SISTEMA DE CONVERSÃO
[1] BÍNARIO
[2] OCTAL
[3] HEXADECIMAL
''')
opção = int(input('Sua opção:'))
if opção == 1:
print('{} em BÍNARIO:{}'.format(num,bin(num)[2:]))
elif opção == 2:
print('{} em OCTAL:{}'.format(num,oct(num)[2:]))
elif opção == 3:
print('{} em HEXADECIMAL:{}'.format(num,hex(num)[2:]))
else:
print('OPÇÃO INVALIDA!') | false |
1c744073c9e13b0b8b00aeda923185ea169b549a | vScourge/Advent_of_Code | /2021/09/2021_day_09_1.py | 2,804 | 4.15625 | 4 | """
--- Day 9: Smoke Basin ---
These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain.
If you can model how the smoke flows through the caves, you might be able to avoid it and be that much safer.
The submarine generates a heightmap of the floor of the nearby caves for you (your puzzle input).
Smoke flows to the lowest point of the area it's in. For example, consider the following heightmap:
2199943210
3987894921
9856789892
8767896789
9899965678
Each number corresponds to the height of a particular location, where 9 is the highest and 0 is the lowest a location can be.
Your first goal is to find the low points - the locations that are lower than any of its adjacent locations.
Most locations have four adjacent locations (up, down, left, and right); locations on the edge or corner of the map
have three or two adjacent locations, respectively. (Diagonal locations do not count as adjacent.)
In the above example, there are four low points, all highlighted: two are in the first row (a 1 and a 0),
one is in the third row (a 5), and one is in the bottom row (also a 5). All other locations on the heightmap have some lower adjacent location, and so are not low points.
The risk level of a low point is 1 plus its height. In the above example, the risk levels of the low points
are 2, 1, 6, and 6. The sum of the risk levels of all low points in the heightmap is therefore 15.
Find all of the low points on your heightmap. What is the sum of the risk levels of all low points on your heightmap?
"""
import numpy
def parse_input( ):
data_list = [ ]
#data = numpy.array( [ ], dtype = numpy.int64 )
for line in open( 'input.txt', 'r' ):
row = [ int( x ) for x in line.strip( ) ]
data_list.append( row )
data = numpy.array( data_list, dtype = numpy.int64 )
# Pad outside of grid with 1 row of -1 values
data = numpy.pad( data, pad_width = 1, mode = 'constant', constant_values = -1 )
return data
data = parse_input( )
answer = 0
for y in range(len( data ) ):
for x in range( len( data[ y ] ) ):
val = data[ y ][ x ]
if val == -1:
continue
vals_slice = numpy.copy( data[ y-1:y+2, x-1:x+2 ] )
vals_slice[0,0] = -1
vals_slice[0,2] = -1
vals_slice[2,0] = -1
vals_slice[2,2] = -1
vals = vals_slice.flatten( )
# Make center value -1 so it gets ignored, since it's the value itself
vals[ 4 ] = -1
adj_vals = [ v for v in vals if v != -1 ]
num_adj = len( adj_vals )
higher_adj_vals = [ v for v in adj_vals if v > val ]
if len( adj_vals ) == len( higher_adj_vals ):
# We found a lowpoint
#print( 'lowpoint =', val, '({0},{1})'.format( x-1,y-1 ) )
risk = 1 + val
answer += risk
print( answer )
# 496 | true |
b247e24618e9c2263362c18b5b47ef5faad97e54 | abhijitsahu/python | /project_01/parse.py | 1,236 | 4.34375 | 4 | #!/usr/bin/python
# Import sys for exit()
import sys
# Import os for checking the file if present
import os.path
# Check if input has provided
if len(sys.argv) <= 1:
print('Enter file name to parse the content: ./sample.py <filename>')
sys.exit()
# Get input file from commandline arg
input_file = sys.argv[1]
# Check if file is present or not
file_present_flag = os.path.isfile(input_file)
# If file is not present ask the user to check if file exist!
if not file_present_flag:
print('Error: Input file \"{}\" is not present!'.format(input_file))
sys.exit()
'''
Steps:
1. Open the file in read mode.
2. Traverse word by word
3. While traversing if the first character is not a capital letter
also last charcater of previuos string ends with '.' then
copy word into list
4. Convert list into string for formatted output screen
'''
list = []
previous_word = ""
with open(input_file, 'r') as fd:
for line in fd:
for word in line.split():
flag = previous_word.endswith('.')
if word[0] >= 'a' and word[0] <= 'z' or flag:
list.append(word)
# print(word)
previous_word = word
parse_string_reslt = ' '.join(list)
print(parse_string_reslt)
| true |
de028eba3f662d85d09305eb24ee3989523344ac | Amirkhan73/Algorithms | /Python/fundamentals/easy/pythonIfElse.py | 648 | 4.46875 | 4 | # Task
# Given an integer, , perform the following conditional actions:
# If is odd, print Weird
# If is even and in the inclusive range of to , print Not Weird
# If is even and in the inclusive range of to , print Weird
# If is even and greater than , print Not Weird
# Input Format
# A single line containing a positive integer, .
# Output Format
# Print Weird if the number is weird; otherwise, print Not Weird.
# Sample Input 0
# 3
# Sample Output 0
# Weird
N = int(input())
if ((N % 2) >= 1) or (N % 2 == 0 and (N >= 6 and N <= 20)):
string = "Weird"
elif (N >= 2 and N <= 5) or N > 20:
string = "Not Weird"
print(string)
| true |
6546d19b2e52da46f3b38810b1d51cb8b6f69fd1 | ianpaulfo/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 1,773 | 4.3125 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
# First-Pass Solution
# Find the maximum for each and every contiguous subarray of size k
# Approach: run a nested loop, the outer loop which will mark the starting point of the subarray of length k,
# the inner loop will run from the starting index to index+k,
# k elements from starting index
# and print the maximum element among these k elements
# 1.Create a nested loop, the outer loop from starting index to n-k th elements. The inner loop will run for k iterations
# 2.Create a variable to store the maximum of k elements traversed by the inner loop
# 3.Find the maximum of k elements traversed by the inner loop
# 4.Print the maximum element in every iteration of outer loop
# method to find the maximum for each and every contiguous subarray of s of size k
def sliding_window_max(arr, k):
max = 0
x = []
# create a nested loop, the outer loop from starting index to nums - k th elements
for i in range(len(arr) - k + 1):
max = arr[i]
# The inner loop will run for k iterations
# create a variable to store the maximum of k elements traversed by the inner loop
for j in range(1, k):
if arr[i + j] > max:
# find the maximum of k elements traversed by the inner loop
max = arr[i + j]
# print the maximum element in every iteration of outer loop
x.append(max)
return x
# Driver method
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")
| true |
a1410bca8d6afc93e4f85f096f37e10982a9a050 | mauricejulesm/python_personal_projects | /creating_files/CreateFiles.py | 895 | 4.125 | 4 | # declare an object name ( just any name)
objectForCreating = open("maurice.txt", "w") # this "w" should be ther to prepare the file for writing on to it
objectForCreating.write("Name: Jules Maurice\n")
objectForCreating.write("Age: 23\n")
objectForCreating.write("School: African Leadership University\n")
objectForCreating.write("Motto: Like Father Like Son - I'm self made\n")
objectForCreating.close() # we close the thing to stop it from keep using the computer;s memory
# now let's read the file content
# then after reading
# we can print out the content to the console
# of course we need an object for reading the file
objectForReading = open("maurice.txt", "r") # also this "r" should be there to help reading
readText = objectForReading.read() # this like passes the text that hav bnn read to the variable created "readText"
print(readText)
objectForReading.close()
| true |
4d92a09dd5ecb17cbd97e6645da78ee8ee4d7316 | arijitsdrush/python | /concept/if-else.py | 270 | 4.15625 | 4 | #!/usr/bin/python3
a, b = 10, 12
# Normal if else
if a > b :
print("a ({}) is greater than b ({})".format(a, b))
else:
print("a ({}) is less than b ({})".format(a, b))
# Ternary Operator
c = ("Greater" if a > b else "Lesser")
print("Value of a is {}".format(c)) | false |
661edcb48e2c8949fb7a4c5315ff3aba10c67369 | eltonlee/Practice | /practice/Notes.py | 1,695 | 4.1875 | 4 | # -------------Arrays----------
# Initalize a array of size k with n stuff inside it
a = ['n']*len(k)
# Loop backwards
for i in range(len(something)-1, -1, -1) # range (start, stop before, step)
# sort the array from lowest to highest
a.sort()
# sort the array from highest to lowest
a.sort(reverse=True)
# Set removes all duplicates in a array.
a = set(a) # [1, 1, 2 ,3] will then be [1, 2, 3]
# finding sum of a array
sum(a)
# using map to multiply 2 arrays
a = [1, 2, 3]
b = [3, 2, 1]
c = map(operator.mul, a, b)
print(list(c))
# we get c = [3, 4, 3]
# using enumerate in a loop gives a it index and its value.
for i, num in enumerate(nums): # i is the index and num is the value.
# if you want to compare current element with next element without going out of bound:
for i in range(len(nums) - 1):
# compare i and i + 1
# -------------Strings --------------
# To replace a character
str = str.replace('a', '') # in this case, it is the character a
# to combine a array of strings with something or nothing
list1 = ['1', '2', '3', '4']
s = '-'
s = s.join(list1) # result is 1-2-3-4
# to sort a string
s = ''.join(sorted(s)) # s is 'bca' but now it is 'abc'
# to reverse a string
s = ''.join(reversed(s))
# To see if a character in a string is a letter
s.isalpha()
# To see if a character in a string is a number
s.isdigit()
# convert a string to all lower case or uppercase:
s = s.lower(), s = s.upper()
# -------------Dictionary---------------------
# To initialize a dict
d = {'a': 0, 'b': 1}
# to get a value from a key
res = d.get('a') # 'a' is the key in this case
# to print out all values of a dictionary
for val in dic.values()
print(val)
| true |
e2ac7e249de6f3381063dc20282b793f4d8d7df1 | jarabt/Python-Academy | /Lekce05/stringToList.py | 379 | 4.15625 | 4 | """
Write a Python program which prompts and accepts a string of comma-separated
numbers from a user and generates a list of those individual numeric strings
converted into numbers.
"""
stringFromUser = input("Please enter comma separated numbers: ")
l = stringFromUser.split(",")
result = []
for word in l:
word = int(word.strip())
result.append(word)
print(result)
| true |
db9d4c1b74746699433293e9f5f690031c9a202a | sharankonety/algorithms-and-data-structures | /Stack/implement_ll.py | 839 | 4.125 | 4 | # Implementing a stack using linked list
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
def pop(self):
if self.head is None:
print("stack underflow")
temp = self.head
temp = temp.next
self.head = temp
def display(head):
while head:
print(head.data,end="-->")
head = head.next
print("/0")
a = Linked_list()
a_nodes = [1,2,3,4,5]
for x in a_nodes:
a.push(x)
display(a.head)
a.pop()
a.pop()
a.pop()
a.pop()
a.pop()
a.pop()
display(a.head) | true |
9bcb72d92a0a5e64765e78c2d112e9b62c96f961 | sharankonety/algorithms-and-data-structures | /Geeks_for_Geeks_Prob's/linked_lists/count_nodes.py | 960 | 4.15625 | 4 | # program to count the number of nodes in the linked list
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def count_list(self):
count = 0
temp = self.head
while temp:
count += 1
temp = temp.next
print(count)
def display(self):
print_val = self.head
while print_val:
print(print_val.data,end="-->")
print_val = print_val.next
print("/0")
def add_data(self,new_data):
new_node = Node(new_data)
if self.head == None:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
list = Linked_list()
list.add_data(1)
list.add_data(2)
list.add_data(3)
list.add_data(4)
list.add_data(5)
list.display()
list.count_list() | true |
dc28c0282c0be6dbc735f7e79e65ce26862a86e6 | sharankonety/algorithms-and-data-structures | /Trees/Binary_Tree/search.py | 1,189 | 4.1875 | 4 | # program to search if a node exists in a tree or not.
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def insert(self,data):
if self.data:
if data<self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data>self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = Node(data)
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data,end=" ")
if self.right:
self.right.PrintTree()
def search(Node,key):
if Node is None:
return
if Node.data == key:
return True
elif key>Node.data:
return search(Node.right,key)
elif key<Node.data:
return search(Node.left,key)
root = Node(25)
root.insert(20)
root.insert(30)
root.insert(19)
root.insert(21)
root.insert(29)
root.insert(31)
root.PrintTree()
print("")
print(search(root,29)) | true |
2a04fec5a4d637fb538a33da170c0bc7c249dda6 | sharankonety/algorithms-and-data-structures | /linked_lists/doubly_linked_lists/create.py | 813 | 4.1875 | 4 | # Inserting in a doubly linked list.
class Node:
def __init__(self,data=None):
self.pre = None
self.data = data
self.next = None
class Doubly_linked_list:
def __init__(self):
self.head = None
self.tail = None
def insert(self,new_data):
new_node = Node(new_data)
if self.head is None:
self.head = self.tail = new_node
self.head.pre = None
self.tail.next = None
else:
self.tail.next = new_node
new_node.pre = self.tail
self.tail = new_node
self.tail.next = None
def display(head):
n = head
while n:
print(n.data,end="-->")
n = n.next
a = Doubly_linked_list()
a_nodes = [1,2,3,4,5]
for x in a_nodes:
a.insert(x)
display(a.head) | true |
b85a8c65a50055d40ed0bd2352b7335055691848 | sharankonety/algorithms-and-data-structures | /linked_lists/linear_linked_lists/deletion/deleting.py | 1,561 | 4.1875 | 4 | class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linked_list:
def __init__(self):
self.head = None
def Print_list(self):
print_val = self.head
while print_val:
print(print_val.data,end="-->")
print_val = print_val.next
print("/0")
# Function to delete the node having the key value
def delete_node(self,key):
# here we need two pointers to point the previous node of the deleted node to the next node of the deleted node.
# so we assign one pointer(p) to the head node and another pointer(q) to None so q is following the pointer.
p = self.head
q = None
# we have two cases 1.key in 1st node 2.key in any other node
# 1. when p is not none and the key value matches with the head node then assign p's next as the head node and assign p as None
if p and p.data == key:
self.head = p.next
p = None
return
# 2. when p is not none and while checking if the key matches with p's data keep traversing with p and q in the linked list
# if the key matches with the data in p then assign p's next to q's next
while p:
if p.data == key:
q.next = p.next
p = None
else:
q = p
p = p.next
list = Linked_list()
list.head = Node(1)
e2 = Node(2)
e3 = Node(3)
list.head.next = e2
e2.next = e3
list.Print_list()
list.delete_node(2)
list.Print_list()
| true |
149cf5b025db9757d37aaedac1f6c097adf89c36 | carlosmanri/Logic-Thinking | /Carlos/Ejercicios-2/IngresoDatos.py | 1,753 | 4.1875 | 4 | def validarnombre(nombre):
while len(nombre)>12 or len(nombre)<6 or nombre.isalnum()==False:
if len(nombre)>12 or len(nombre)<6:
print("El usuario debe tener un mínimo de 6 caracteres y un máximo de 12.")
if nombre.isalnum()==False:
print("El nombre de usuario solo puede contener letras y números")
nombre = input("Introduzca un nuevo nombre de usuario: ")
print("Usuario válido")
return True
def validarcontraseña(contraseña):
while chr(32) in contraseña or len(contraseña)<8 or contraseña.isalnum()==True or contraseña.islower()==True or contraseña.isupper()==True or contraseña.isdigit()==True:
if chr(32) in contraseña:
print("No puede haber espacios en la contraseña. ")
if len(contraseña)<8:
print("La contraseña debe contener un mínimo de 8 caracteres. ")
if contraseña.isalnum()==True:
print("La contraseña debe contener al menos un caracter no alfanumérico. ")
if contraseña.islower()==True:
print("La contraseña debe contener al menos una mayúscula. ")
if contraseña.isupper()==True:
print("La contraseña debe contener al menos una minúscula. ")
if contraseña.isdigit()==True:
print("La contraseña debe contener letras. ")
print("La contraseña es segura")
contraseña = input("Introduzca una nueva contraseña: ")
print("La contraseña es segura. ")
return True
#Fin de declaración de funciones
nombre = input("Introduzca un nombre de usuario: ")
validarnombre(nombre)
contraseña = input("Introduzca una contraseña: ")
validarcontraseña(contraseña)
print("Datos introducidos correctamente. ")
| false |
f252cf151ced6f28de04b9e72fedc98d103360ba | ayush-206/python | /assignment13.py | 1,976 | 4.375 | 4 | #Q.1- Name and handle the exception occured in the following program:
a=3
if a<4:
try:
a=a/(a-3)
except Exception:
print("an Exception occured")
#Q.2- Name and handle the exception occurred in the following program:
l=[1,2,3]
try:
print(l[3])
except Exception:
print("an exception occured")
#Q.3- What will be the output of the following code:
# Program to depict Raising Exception
try:
raise NameError("Hi there") # Raise Error
except NameError:
print("An exception")
raise # To determine whether the exception was raised or not
#Q.4- What will be the output of the following code:
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print("a/b result in 0")
else:
print(c)
# Driver program to test above function
# AbyB(2.0, 3.0)
# AbyB(3.0, 3.0)
#Q.5- Write a program to show and handle following exceptions:
# 1. Import Error
#before handling
import python
print("hello world")
#after handling
try:
import boy
print("hello world")
except Exception:
print("exception occured")
("hello world")
#after handling
#2 . Value error
#before handling
n=int(input("enter a number"))
print("enter a number",n)
#after handling
try:
n=int(input("enter a number:"))
print(n)
except Exception:
print("value error")
#3 . index error
#before handling
l=[1,2,3]
print(l[4])
#after handling
l=[1,2,3]
try:
print(l[4])
except Exception:
print("index error")
#Q.6- Create a user-defined exception AgeTooSmallError() that warns the user when they have entered age less than 18.
#The code must keep taking input till the user enters the appropriate age number(less than 18).
class AgeTooSmallError(Exception):
pass
a=1
while True:
print("you have to enter the age 18 or more than 18")
try:
a=int(input("enter the age:"))
if a<18:
raise AgeTooSmallError()
print("Correct")
break
except Exception:
print("Incorrect Age")
| true |
2fe4a1d7dabf7e49da3bd244c1957287a7c7604c | Oybek-uzb/py_full_course | /py_full_course/21_stirng_format.py | 1,867 | 4.1875 | 4 | animal = "dog"
item = "moon"
print("The " + animal + " jumped over the " + item)
print("The {} jumped over the {}".format(animal, item)) # yuqoridagiga alternativ
print("The {1} jumped over the {0}".format(animal, item)) # positional arguments, bu usul bilan format ni ichiga berilgan argumentlarning qaysi tartibda turgani qayerga qo'yilishi kerakligini ko'rsatish mumkin.
print("The {animal_1} jumped over the {item_1}".format(animal_1="cat", item_1="tree")) # keyword arguments
# aynan bir indeksni yoki keyword ni bir nech marta ishlatishimiz ham mumkin, print("{one} {one}".format(one="1", two="2"))
print("My name is {:10}. Nice to meet you!".format("Oybek")) # {:10} yozuvi qiymat uchun 10 ta joy ajratish degani.
print("My name is {:<10}. Nice to meet you!".format("Oybek")) # yuqoridagi bilan bir xil.
print("My name is {:>10}. Nice to meet you!".format("Oybek")) # bunda ham 10 ta joy ajratiladi yuqoridagilardan farqi ortib qolgan joy qiymatdan chap tomonga o'tkaziladi.
print("My name is {:^10}. Nice to meet you!".format("Oybek")) # bunda ham shu holat faqat ortib qolgan joy qiymatning ikki tomoniga taqsimlanadi.
# format numbers
number_pi = 3.14159
print("The number pi is {:.2f}".format(number_pi)) # number_pi dagi verguldan keyingi 2 ta sonni yaxlitlab chiqaradi.
number = 1000
print("The number is {:,}".format(number)) # 10,000 ko'rinishida yozadi, ya'ni har uch xonadan keyin (,) qo'yadi.
print("The number is {:b}".format(number)) # number ni binar ko'rinishga, ya'ni ikkilik sanoq sistemasiga o'tkazadi.
print("The number is {:o}".format(number)) # number ni sakkizlik sanoq sistemasiga o'tkazadi.
print("The number is {:x}".format(number)) # number ni o'n oltilik sanoq sistemasiga o'tkazadi. {:X} katta harflar uchun.
print("The number is {:e}".format(number)) # number ni o'nning darajasi ko'rinishida yozadi. {:E} katta harf uchun.
| false |
f90231f573c38e66952d5a0f6c1b6f3d9209d819 | Jdamianbello2/cs190 | /CS190/venv/crashcourse.py | 987 | 4.34375 | 4 | name = "salad head"
print(name.upper())
print(name.lower())
simple_message = "I like you too"
print(simple_message)
print("The language 'Python' is named after Monty Python, not the snake.")
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
message = "Hello, " + full_name.title() + "!"
print(message)
print("Language:\nPython\nC\nJavaScript")
favorite_language = "python "
favorite_language.rstrip()
favorite_language = favorite_language.rstrip()
print(favorite_language)
print(2 * 3)
print(2 ** 3)
age = 23
birthday = "Happy " + str(age) + "rd Birthday!"
print(birthday)
# Say hello to everyone,
print("Hello Python people!")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + "is odd.")
if x = 42:
print("x equals 42")
| true |
47c7676763843267376b3c17461f418bd285f394 | samipsairam/PythonDS_ALGO | /basics/Dictionary_Tut.py | 1,577 | 4.1875 | 4 | # Dictionary is another data structure which in other language is called as 'HashTable' or 'Map' or 'Object' in another language
# Dictionary or dict is a data type or data structure itself
# Have KV pairs
# Dictionary is unordered Key-Value pairs, Unlike List they are not ordered hence cannot be get by index
dictionary = {
'a': [1, 2, 3],
'b': 'hello',
'x': True
}
print(dictionary['a'])
print(dictionary['a'][1])
# list of dict
my_list = [
{
'a': [1, 2, 3],
'b': 'Hello',
'c': True
},
{
'a': [4, 5, 6],
'b': 'World',
'c': False
}
]
print(my_list[0]['a'][2])
'''
LIST vs DICT use:
orderd => list, unorderd => dict
more_information => dict
'''
# Dictionary Keys
# Keys shouldn't be Immutable
# Keys should be unique else it would override the old assignement
dict1 = {
123: [1, 2, 3],
True: 'Hello',
'grey': True # keys should be immutable so gives 'Unhashable TypeError'
}
print(dict1)
user = {
'basket': [1,2,3],
'greet': 'hello',
'height': 5.2
}
print(user.get('age')) # give None if no age key exists
print(user.get('name','DEMOIN')) # adds default value if name key doesnot exists
print(user.get('height',0.0))
# user2 = dict(name = 'JohnHon')
# finding item in dict
print('basket' in user)
print('size' in user)
print('greet' in user.keys())
print('hello' in user.values())
print(user.items())
user2 = user.copy()
print(user2)
user.clear()
print(user)
print(user2)
print(user2.pop('greet'))
print(user2)
user2.update({'age':55})
print(user2) | true |
df4626c4f30fa2562000de499a79170be1969bd1 | diegoortizmatajira/python-learning | /classes/20210721/Chapter-9-Practice.py | 2,944 | 4.28125 | 4 | import datetime
def task01():
print("=========================\nTask 1\n-------------------------")
birth_date = datetime.date(1982, 5, 1)
print(f"Your birthday is: {birth_date}")
today = datetime.date.today()
print(f"Today is {today}")
age = today - birth_date
print(f"Your age today is {age.days // 365}")
def task02():
print("=========================\nTask 2\n-------------------------")
college_start_date = datetime.date(2021, 5, 3)
print(f"Your college start was in: {college_start_date}")
today = datetime.date.today()
print(f"Today is {today}")
college_age = today - college_start_date
print(f"You have {college_age.days // 30} months in college")
task01()
task02()
def practice01():
print("=========================\nPractice 1\n-------------------------")
today = datetime.date.today()
print(f"Today is {today:%A}")
def practice02():
print("=========================\nPractice 2\n-------------------------")
today = datetime.datetime.today()
birthday_str = input('Please enter the birthday date in YYYY-MM-DD format: ')
year, month, day = map(int, birthday_str.split('-'))
# Builds the actual birthday date
birthday_date = datetime.datetime(year, month, day)
print(f'Your birthday is: {birthday_date:%b %d %Y}')
age = today - birthday_date
print(f"Your age today is {age.days // 365}")
next_birthday_date = datetime.datetime(today.year, birthday_date.month, birthday_date.day)
if next_birthday_date <= today:
next_birthday_date = datetime.datetime(today.year + 1, birthday_date.month, birthday_date.day)
print(f'Your next birthday is on: {next_birthday_date:%b %d %Y}')
days_to_next_birthday = next_birthday_date - today
seconds = days_to_next_birthday.seconds
hours = seconds // 3600
seconds = seconds - hours * 3600
minute = seconds // 60
seconds = seconds - minute * 60
print(f'You need to wait {days_to_next_birthday.days} days, {hours} hours, {minute} minutes, {seconds} seconds')
def practice03():
print("=========================\nPractice 3\n-------------------------")
today = datetime.datetime.today()
birthday_str = input('Please enter the birthday date in YYYY-MM-DD format: ')
year, month, day = map(int, birthday_str.split('-'))
# Builds the actual birthday date
birthday_date = datetime.datetime(year, month, day)
age = birthday_date - today
print(f'You have lived {age.seconds} seconds')
def practice04():
print("=========================\nPractice 4\n-------------------------")
today = datetime.datetime.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
print(f'Today is: {today:%b %d %Y}')
print(f'Yesteday was: {yesterday:%b %d %Y}')
print(f'Tomorrow will be: {tomorrow:%b %d %Y}')
practice01()
practice02()
practice03()
practice04()
| false |
8643f4628e3b260434ff2475e0c5fb1a85f5832d | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios alternativas/Ejercicio 12.py | 424 | 4.21875 | 4 |
#Escribir un programa que lea un año indicar si es bisiesto.
#Nota: un año es bisiesto si es un número divisible por 4, pero no si es divisible por 100,
#excepto que también sea divisible por 400.
anyo = int(input("Dime un año:"))
if (anyo % 4 == 0 and anyo % 100 != 0) or (anyo % 4 == 0 and anyo % 100 == 0 and anyo % 400 == 0):
print("El año es bisiesto.")
else:
print("El año no es bisiesto.")
| false |
33ee2c047ab99d11285c9a7f71776e4d2451f163 | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios diccionarios/Ejercicio 4.py | 1,398 | 4.125 | 4 |
#Codifica un programa en python que nos permita guardar los nombres de los alumnos de una clase
#y las notas que han obtenido. Cada alumno puede tener distinta cantidad de notas.
#Guarda la información en un diccionario cuya claves serán los nombres de los alumnos
#y los valores serán listas con las notas de cada alumno.
#El programa pedirá el número de alumnos que vamos a introducir,
# pedirá su nombre e irá pidiendo sus notas hasta que introduzcamos un número negativo.
# Al final el programa nos mostrará la lista de alumnos
#y la nota media obtenida por cada uno de ellos.
#Nota: si se introduce el nombre de un alumno que ya existe el programa nos dará un error.
diccionario = {}
lista = []
total = 0
num = int(input("Dime la cantidad de alumnos: "))
for i in range(0,num):
nombre = str(input("Dime el nombre del alumno: "))
if nombre in diccionario.keys():
print("ERROR. Programa finalizado.")
break;
nota = 0
while nota >= 0:
nota = int(input(f"Dime la nota de {nombre}: "))
if nota < 0:
break;
lista.append(nota)
diccionario[nombre] = lista
lista = []
print(diccionario)
for i in diccionario.keys():
print(i,"tiene una nota media de ",end="")
for media in diccionario[i]:
total = total + media
print(total / len(diccionario[i]))
total = 0
| false |
caf15d215cc73a389f11351d123ff65bd3de4a4e | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Entrega 1/Ejercicio 3.py | 1,106 | 4.28125 | 4 |
#Escriba un programa que pida tres números y que escriba si son los tres iguales, si hay dos iguales o si son los tres distintos.
#COMPARADOR DE TRES NÚMEROS
#Escriba un número: 6
#Escriba otro número: 6
#Escriba otro número más: 6
#Ha escrito tres veces el mismo número.
#COMPARADOR DE TRES NÚMEROS
#Escriba un número: 6
#Escriba otro número: 6.5
#Escriba otro número más: 6
#Ha escrito uno de los números dos veces.
#COMPARADOR DE TRES NÚMEROS
#Escriba un número: 4
#Escriba otro número: 5
#Escriba otro número más: 6
#Los tres números que ha escrito son distintos.
print("COMPARADOR DE TRES NÚMEROS")
num1 = int(input("Escriba un número: "))
num2 = int(input("Escriba otro número: "))
num3 = int(input("Escriba otro número más: "))
if num1 == num2 and num1 == num3:
print("Ha escrito tres veces el mismo número.")
elif num1 == num2 or num2 == num3 or num1 == num3:
print("Ha escrito uno de los números dos veces.")
elif num1 != num2 and num1 != num3 and num2 != num3:
print("Los tres números que ha escrito son distintos.")
| false |
5008d3855f3271694ca799cebb4a2939f9b14245 | ManuelLoraRoman/Apuntes-1-ASIR | /LM/PYTHON/Ejercicios diccionarios/Ejercicio 3.py | 989 | 4.125 | 4 |
#Vamos a crear un programa en python donde vamos a declarar un diccionario para guardar los precios de las distintas frutas.
#El programa pedirá el nombre de la fruta y la cantidad que se ha vendido
#y nos mostrará el precio final de la fruta a partir de los datos guardados en el diccionario.
# Si la fruta no existe nos dará un error. Tras cada consulta el programa nos preguntará si queremos hacer otra consulta.
diccionario = {"Kiwi": 1.80,"Naranja": 1.50,"Mango": 3.20,"Limón": 1.10,"Ciruela": 3.25,"Higo": 4.20,"Plátano": 1.89}
indicador = "s"
while indicador.lower() == "s":
fruta = str(input("Dime la fruta deseada: "))
if fruta not in diccionario:
print("ERROR")
cantidad = int(input(f"Dime la cantidad de {fruta}: "))
print("Precio Final: ",diccionario[fruta] * cantidad,"€.")
indicador = str(input("¿Quieres realizar otra consulta? "))
if indicador.lower() == "n":
print("Programa finalizado")
break;
| false |
aad213697313f4f67d999af41119d0e172cae57a | LiuHB2096/Backup | /notes1.py | 421 | 4.28125 | 4 | # This is a comment, use them very often
print (4 + 6) # addition
print (-4 - 5) # subtraction
print (6 * 3) # multiplication
print (8 / 3) # Division
print (3 ** 3) # exponents- 3 to the 3rd power
print (10 % 3) # modulo - gives you the remainder
print (15 % 5)
print (9 % 4)
print (16 % 3)
print (16 % 7)
# to make variable, think of a name
name = input("What is your name?: ")
print("Hello " + name) | true |
c299f3c87a9935300a0880b7ad7bfa599bd39f6b | divya-nk/hackerrank_solutions | /Python-practice/Strings/captilize.py | 425 | 4.21875 | 4 | import string
def solve(s):
return string.capwords(s, ' ')
# Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.
| true |
59bd1f32dd0cb7ed6f999c0079670b852527787c | Nathhill92/PY4E_Exercise | /Code Challenges/ReducePractice.py | 840 | 4.1875 | 4 | #return max
import functools
lis = [ 1 , 3, 5, 6, 2, ]
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
# ruber ducky walkthrough:
# reduce takes two arguments,
# the function logic and the list to to perform the function logic on
# The value of returned by the logic serves as the "a" value for future iterations of this function
# A one value bubble sort
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
# return product
print ("The product of the list elements is: ",end='')
print(functools.reduce(lambda a,b: a*b,lis))
#find smallest item in list
print("The smmalles item in the lost elements is:",end="")
print(functools.reduce(lambda x,y: x if x < y else y,lis))
| true |
b872bc0979aab82371c80794eebd6dc61b1dab91 | Nathhill92/PY4E_Exercise | /Code Challenges/ColorInverter.py | 649 | 4.46875 | 4 | # Create a function that inverts the rgb values of a given tuple.
# Examples
# color_invert((255, 255, 255)) ➞ (0, 0, 0)
# # (255, 255, 255) is the color white.
# # The opposite is (0, 0, 0), which is black.
# color_invert((0, 0, 0)) ➞ (255, 255, 255)
# color_invert((165, 170, 221)) ➞ (90, 85, 34)
# Notes
# Must return a tuple.
# 255 is the max value of a single color channel.
def colorinvert(rgb):
colorrange = list(range(0, 256))
newrgb = list()
for x in range(0, len(rgb)):
y = colorrange[(-rgb[x])-1]
newrgb.append(y)
return newrgb
print(colorinvert([255,255,255]))
print(colorinvert([165,170,221])) | true |
33c48b23e18d00aa230254ee18f1e48a62b29138 | Nathhill92/PY4E_Exercise | /Code Challenges/OOPCalculator.py | 1,061 | 4.53125 | 5 | # Simple OOP Calculator
# Create methods for the Calculator class that can do the following:
# Add two numbers.
# Subtract two numbers.
# Multiply two numbers.
# Divide two numbers.
# Examples
# calculator = Calculator()
# calculator.add(10, 5) ➞ 15
# calculator.subtract(10, 5) ➞ 5
# calculator.multiply(10, 5) ➞ 50
# calculator.divide(10, 5) ➞ 2
# Notes
# The methods should return the result of the calculation.
# Don't worry about needing to handle division by zero errors.
# See the Resources tab for some helpful tutorials on Python classes. - https://edabit.com/challenge/ta8GBizBNbRGo5iC6
class Calculator:
@staticmethod
def add(x,y):
return x+y
@staticmethod
def subtract(x,y):
return x-y
@staticmethod
def multiply(x,y):
return x*y
@staticmethod
def divide(x,y):
return x/y
x=50
y=5
print("x =",x,"y =",y)
print()
print("x + y =",Calculator.add(x,y))
print("x - y =",Calculator.subtract(x,y))
print("x * y =",Calculator.multiply(x,y))
print("x / y =",Calculator.divide(x,y))
| true |
b38c4fc99ad9bfafa16e07237e3dcb2f89c0496e | Nathhill92/PY4E_Exercise | /chap2.py | 1,177 | 4.625 | 5 | #Chapter 2 exercises
#https://www.py4e.com/html3/02-variables
#Write a program that uses input to prompt the user for their name and then welcomes them
# name = input("Hello! What is your name? ")
# print("Hello " +name)
# print()
#Write a program to prompt users for hours and hourly rate to compute gross wage
hours = input("Enter hours: ")
rate = input("Hourly rate: ")
pay = float(hours) * float(rate)
print("Pay $" + str(round(pay, 2)))
#Exercise 4: Assume that we execute the following assignment statements:
# width = 17
# height = 12.0
# For each of the following expressions, write the value of the expression and the type (of the value of the expression).
# width//2
# width/2.0
# height/3
# 1 + 2 * 5
width = 17
height = 12.0
print(width//2)
print(type(width//2))
print(width/2.0)
print(type(width/2.0))
print(height/3)
print(type(height/3))
print(1+2*5)
print(type(1+2*5))
print()
#Exercise 5: Write a program which prompts the user for a Celsius temperature,
# convert the temperature to Fahrenheit, and print out the converted temperature.
tempInCel = float(input("Temp in C: "))
tempInFar = tempInCel * (9/5) + 32
print("Temp in F: " +str(tempInFar)) | true |
71ac0a3e35fa69cdaf0574332f49a51213594dc7 | Hassan-Farid/DAA-Assignments | /Minimum Numbers/QuadraticMin.py | 670 | 4.21875 | 4 | def findQuadMin(arr):
'''
Sorts the values in the given array in O(n^2) time in ascending order
and returns the first index value i.e. minimum value
'''
for j in range(1, len(arr)):
key = arr[j]
i = j - 1
while i >= 0 and arr[i] > key:
arr[i+1] = arr[i]
i -= 1
arr[i+1] = key
return arr[0]
if __name__ == "__main__":
numbers = input('Enter the numbers for the array, seperated by a comma: ')
numbers = numbers.split(',')
numArray = list(map(int, numbers))
print('The minimum value in the provided array is: {}'.format(findQuadMin(numArray)))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.