blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
7f4246df5871b86d5f6bd5e6d55e15780dd98f6e | nbiadrytski-zz/python-training | /dive_into_p3/classes/person3.py | 1,004 | 4.28125 | 4 | import datetime
class Person3:
def __init__(self, name, surname, birthdate, address, phone, email): # params passed to __init__ method
self.name = name # attribute
self.surname = surname
self.birthdate = birthdate
self.address = address
self.phone = phone
self.email = email
# whenever we call a method on an object,
# the object itself is automatically passed in as the first parameter (self)
def get_age(self): # instance method
today = datetime.date.today()
age = today.year - self.birthdate.year
if today < datetime.date(today.year, self.birthdate.month, self.birthdate.day):
age -= 1
return age
person = Person3( # # person is an instance of Person3 class
'Jane',
'Doe',
datetime.date(1986, 3, 31),
'Minsk, Nezavisimosti pr-t, 165-2',
'333 45 87',
'jane.doe@mail.com'
)
print(person.name)
print(person.email)
print(person.get_age())
for key in ["a", "b", "c"]:
print(mydict[key]) | false |
aa82cfb605e7cec0fff586fa9e24b9e8bf0df80e | NataliiaBidak/py-training-hw | /decorators.py | 1,667 | 4.1875 | 4 | """Write a Decorator named after5 that will ignore the decorated function in the first 5 times it is called. Example Usage:
@after5
def doit(): print("Yo!")
# ignore the first 5 calls
doit()
doit()
doit()
doit()
doit()
# so only print yo once
doit()
please make a similar one, but that acceps times to skip as param (@after(<times_to_skip>))
=========================
Calculation in the following fib function may take a long time. Implement a Decorator that remembers old calculations so the function won't calculate a fib value more than once. Program Code:
@memoize
def fib(n):
print("fib({})".format(n))
if n <= 2:
return 1
else:
return fib(n-1) + fib(n-2)
Expected Output:
fib(10)
fib(9)
fib(8)
fib(7)
fib(6)
fib(5)
fib(4)
fib(3)
fib(2)
fib(1)
55
=======================
Write a decorator called accepts that checks if a function was called with correct argument types. Usage example:
# make sure function can only be called with a float and an int
@accepts(float, int)
def pow(base, exp):
pass
# raise AssertionError
pow('x', 10)
========================
Write a decorator called returns that checks that a function returns expected argument type. Usage example:
@returns(str)
def same(word)
return word
# works:
same('hello')
# raise AssertionError:
same(10)
=========================
Write a decorator named logger. It should log function calls and execution
time (for example: function f was called w/ params <a, b> and took <time> to execute). Decorator may accept argument file - file to write logs to. If no param was provided - simply print logs to console.
Decorator should be implemented as a class.
"""
| true |
34b404276601227ab7d713cd2ee6cfa1839e7969 | ddjaell/algorithm | /Stack.py | 524 | 4.15625 | 4 | """
스택은 LIFO, FILO의 형태가 있다
"""
"""
python의 list는 기본적으로 스택의 구조를 가지고 있음
"""
stack_list = list()
stack_list.append(1)
stack_list.append(2)
stack_list.append(3)
print(stack_list)
print(stack_list.pop())
print("after pop() once = ", stack_list)
"""
pop(), push() 함수 만들어보기
"""
stack_self = list()
def push(data):
stack_self.append(data)
def pop():
tmp = stack_self[-1]
del stack_self[-1]
print(tmp)
for i in range(10):
push(i)
pop() | false |
7498e0e3d6658736c53c800a929fa12472bd36f6 | kura123/language_processing100 | /chapter1/03.py | 497 | 4.125 | 4 | # 03. 円周率Permalink
# “Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,
# 各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
string = 'Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.'
string = string.replace(',','').replace('.','')
result = [len(word) for word in string.split()]
print(result) | false |
b309163a54cb56b9f9c3b21795388a74658910fb | 99zraymond/Daily-Lesson-Exercises | /Daily Exercise 02082018.py | 770 | 4.34375 | 4 | #Your Name - Python Daily Exercise - date of learning
# Instructions - create a file for each of the daily exercises, answer each question seperately
# 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice).
# 2. Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old. Clue input()
#3 Write a program that prints out the numbers from 1 to 20.
# For multiples of three, print "usb" instead of the number and for the mulitiples of five, print "device".
# For numbers which are multiples of both three and five, print "usb device".
# Print a new line after each string or number.
| true |
505c59d5b7161eab01c637f144f7f3bf790f2bfb | manjunath2019/Python_7am_May_2019 | /Operators/Membership.py | 452 | 4.15625 | 4 |
"""
in and not in are the membership operators in python
Are used to test whether a value or variable is found in a sequence
(String, List, Tuple, & Dictrionary)
"""
x_value = 'Guido Van Rossum'
y_value = {1:'a',2:'b'}
print(x_value)
print(y_value)
#a = input('Enter a Value : ')
#print(a in x_value.lower())
print(1 in y_value)
print('b' in y_value)
print('R' not in x_value)
# Account_Name = input('Enter Your Account Name : ')
# print(Account_Name) | true |
0934c83a40bffa4b7abc9caf0235b71cf2e536fa | cylinder-lee-cn/LeetCode | /LeetCode/819.py | 2,435 | 4.28125 | 4 | """
819. 最常见的单词
给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。
题目保证至少有一个词不在禁用列表中,而且答案唯一。
禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。
示例:
输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输出: "ball"
解释:
"hit" 出现了3次,但它是一个禁用的单词。
"ball" 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。
注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 "ball,"),
"hit"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
说明:
1 <= 段落长度 <= 1000.
1 <= 禁用单词个数 <= 100.
1 <= 禁用单词长度 <= 10.
答案是唯一的, 且都是小写字母 (即使在 paragraph 里是大写的,即使是一些特定的名词,答案都是小写的。)
paragraph 只包含字母、空格和下列标点符号!?',;.
paragraph 里单词之间都由空格隔开。
不存在没有连字符或者带有连字符的单词。
单词里只包含字母,不会出现省略号或者其他标点符号。
"""
class Solution:
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
paragraph = paragraph.replace('!', '').replace('?', '').replace(
',', '').replace(';', '').replace('.', '').replace('\'', '')
dp = {}
words = paragraph.split(' ')
maxl = 0
maxw = ''
for word in words:
word = word.lower()
if (word not in banned):
times = dp.get(word, 0) + 1
if (times > maxl):
maxl = times
maxw = word
dp[word] = times
print(dp, maxl, maxw)
return maxw
s = Solution()
print(s.mostCommonWord("abc abc? abcd the jeff!", ["abc", "abcd", "jeff"]))
# print(
# s.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.",
# ["hit"]))
| false |
c30de23d2ac7f09d0b389dcee2b313b231c7daa4 | cylinder-lee-cn/LeetCode | /LeetCode/98.py | 1,808 | 4.375 | 4 | """
98. 验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.result = []
def inorderTraversal(self, root):
if (root is not None):
self.inorderTraversal(root.left)
self.result.append(root.val)
self.inorderTraversal(root.right)
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.inorderTraversal(root)
print(self.result)
return self.result == sorted(self.result) and len(self.result) == len(
set(self.result))
r1 = TreeNode(5)
r1l = TreeNode(1)
r1r = TreeNode(4)
r1rl = TreeNode(3)
r1rr = TreeNode(6)
r1.left = r1l
r1.right = r1r
r1r.left = r1rl
r1r.right = r1rr
s = Solution()
print(s.isValidBST(r1))
"""
此题解法:
* 所有左子树的值小于根节点,所有右子树的值大于根节点
* 根据这个特征,使用中序遍历,有效的二叉搜索树遍历后是个增序数组
* 只要遍历后的数组和排序后数组比较一下就知道
"""
| false |
8bd7f0c881b93d5836a57cca17561cefed3ab1de | cylinder-lee-cn/LeetCode | /LeetCode/75.py | 1,700 | 4.28125 | 4 | """
75. 颜色分类
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,
使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
"""
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
left, right = -1, len(nums)
i = 0
while (i < right):
if (nums[i] == 1):
i = i + 1
elif (nums[i] == 2):
right = right - 1
nums[right], nums[i] = nums[i], nums[right]
else:
left = left + 1
nums[left], nums[i] = nums[i], nums[left]
i = i + 1
print(nums)
s = Solution()
s.sortColors([2, 0, 2, 1, 1, 0])
"""
此题解法:
* 使用了3指针,最左(指向0),最右(指向2),i是当前元素指针
* 遍历nums,当元素是1时,不做动作,i增1
* 当是2时,换到最右边,并且最右边指针向左挪1
* 当是0时,换到最左边,并且最左指针向右挪一位,同时i增1
"""
| false |
b8a9793d228c4d34d48b28d6d86c402270de4ace | cylinder-lee-cn/LeetCode | /LeetCode/384.py | 1,519 | 4.28125 | 4 | """
384. 打乱数组
打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
"""
import random
class Solution:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.old = list(nums)
self.nums = list(nums)
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.old
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
random.shuffle(self.nums)
return self.nums
# Your Solution object will be instantiated and called as such:
obj = Solution({1, 2, 3})
param_2 = obj.shuffle()
param_1 = obj.reset()
print(param_1)
print(param_2)
"""
此题解法:
* 主要考察随机数的使用。
* 一个数组的“均匀打乱”,比较好的是使用“Fisher-Yates shuffle”算法。
-- To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
j ← random integer such that 0 ≤ j ≤ i
exchange a[j] and a[i]
"""
| false |
6140d410e7091956e4ae5c7d42f438843ac972b7 | cylinder-lee-cn/LeetCode | /LeetCode/344.py | 507 | 4.3125 | 4 | """
344. 反转字符串
编写一个函数,其作用是将输入的字符串反转过来。
示例 1:
输入: "hello"
输出: "olleh"
示例 2:
输入: "A man, a plan, a canal: Panama"
输出: "amanaP :lanac a ,nalp a ,nam A"
"""
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
s = Solution()
print(s.reverseString('hello'))
print(s.reverseString('A man, a plan, a canal: Panama'))
| false |
a012a2254bf132917c05470cbba7e0e7e58aa997 | cylinder-lee-cn/LeetCode | /LeetCode/206.py | 1,126 | 4.15625 | 4 | """
206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if (head is None or head.next is None):
return head
pre=None
cur=head
newhead=cur
while cur:
newhead=cur
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return newhead
l1=ListNode(1)
l2=ListNode(2)
l3=ListNode(3)
l4=ListNode(4)
l5=ListNode(5)
l1.next=l2
l2.next=l3
l3.next=l4
l4.next=l5
s=Solution()
p=s.reverseList(l1)
while p:
print(p.val)
p=p.next
"""
循环的方法中,使用pre指向前一个结点,cur指向当前结点,每次把cur->next指向pre即可。
""" | false |
54dc735d569e57a8866fcae50dfc75254dabde04 | cylinder-lee-cn/LeetCode | /LeetCode/876.py | 2,078 | 4.21875 | 4 | """
876. 链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
提示:
给定链表的结点数介于 1 和 100 之间。
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
chain_i = head
chain_j = head
while 1:
if (chain_j.next is None):
return chain_i
if (chain_j.next.next is None):
return chain_i.next
chain_i = chain_i.next
chain_j = chain_j.next.next
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l6 = ListNode(6)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
l5.next = l6
s = Solution()
# print(s.middleNode(l1), l1.val)
print(s.middleNode(l1))
"""
此题解法:找链表的中心点,最标准就是使用’快、慢‘指针,慢指针一次走一位,快指针一次走两位。
* 当快指针走到尾部时,慢指针正好走了一半。
* 快指针走到尾部的含义是 快.next is None 或者是 快.next.next is None
* 如果是偶数个元素,中间其实指的是中间2个元素,慢指针正好停在前一个,如果要后一个的话就取 慢.next
"""
| false |
31199be0e0349f61fe8df709be933f29da645805 | cylinder-lee-cn/LeetCode | /LeetCode/144.py | 819 | 4.125 | 4 | """
144. 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ret = []
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if (root is not None):
self.ret.append(root.val)
self.preorderTraversal(root.left)
self.preorderTraversal(root.right)
return self.ret
| false |
9d557f02cbbfaa882e68b2e617d6f8a09992460a | cylinder-lee-cn/LeetCode | /LeetCode/151.py | 1,100 | 4.3125 | 4 | """
151. 翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: "the sky is blue",
输出: "blue is sky the".
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。
"""
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
# s_r = s.split(' ')[::-1]
# return ' '.join(w for w in s_r if w != '')
return ' '.join(reversed(s.split()))
s = Solution()
print(s.reverseWords("the sky is blue"))
"""
此题解法:
* python字符串的split方法中分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
* 不使用带参数的split方法,就直接过滤掉了多余的空格。
* 利用
"""
| false |
ba05240853d5865e4a57d9593bd3bcdf97696bb7 | run-fourest-run/IteratorProtocol | /realpythonitertools/itertoolsintro.py | 539 | 4.1875 | 4 | '''itertools is a module that implements a number of iterator building blocks. Functions in itertools operate
on iterators to produce more complex iterators'''
test_list_0 = [95000,95000,95000,95000]
test_list_1 = [117000,117000,121000,120000]
test_list_2 = ['alex','joe','anthony','david']
'''zip example'''
def see_zip_type():
return_iterator = zip(test_list_1,test_list_2)
print(return_iterator)
print(list(zip(test_list_1,test_list_0)))
print (list(map(len,test_list_2)))
print (list(map(sum,zip(test_list_1,test_list_0)))) | true |
e0d48e5df6768de714b9928cc4853cb92b121535 | run-fourest-run/IteratorProtocol | /itertoolsdocs/chain.py | 720 | 4.1875 | 4 | import itertools
'''
Make an iterator that returns elements from the first iterable until its exhausted. Then proceed to the next
iterable, until all the iterables are exhausted.
Used for treating consecutive sequences as a single sequence
'''
def chain(*iterables):
for it in iterables:
for element in it:
yield element
def from_iterable(iterable):
# itertools.chain.from_iterable(['abc','def']) -> a b c d e f
for it in iterable:
for element in it:
yield element
data1 = [10,20,30,40,50]
data2 = [60,70,80,90,100]
chained_data = itertools.chain(data1,data2)
it = iter(data1)
it1 = next(it)
print(it1)
it1 = next(it)
print(it1)
it2 = next(it)
print(it1,it2)
| true |
ec7199c351470743b5ead5d6639229d283ecfca7 | bc-uw/IntroPython2016 | /students/bc-uw/session04/trigram.py | 949 | 4.125 | 4 | """
Trigram lab attempt.
Version0.I don't understand what this is supposed to do
"""
import sys
import string
import random
def sourceFile_to_list(input_file):
"""
list comprehension to iterate through source file lines
and add them to textlist
"""
with open(input_file) as f:
textlist = [line.strip().lower() for line in f]
return textlist
def makeTrigram(sourcelist):
"""
This function takes a list of words as input
It then uses zip to merge words together and???
"""
trigramzip = zip(sourcelist, sourcelist[1:], sourcelist[2:])
#I can iterate through this zip
if __name__ == "__main__":
#from solutions, taking filename as an arg
try:
filename = sys.argv[1]
except IndexError:
print("You must pass in a filename")
sys.exit(1)
#let's get the source file into a list
sourceFile_to_list(filename)
#let's split the list into words?
| true |
8f995f5ec8b53e07ea81997683fb7acd957a5acc | naymajahan/Object-Oriented-programming1 | /python-regular-method.py | 979 | 4.34375 | 4 | #### object oriented programming in python
class StoryBook:
def __init__(self, name, price, authorName, authorBorne, no_of_pages):
# setting the instance variables here
self.name = name
self.price = price
self.authorName = authorName
self.authorBorne = authorBorne
self.publishingYear = 2020
self.no_of_pages = no_of_pages
# Regular method 1
def get_book_info(self):
print(f'The book name: {self.name}, price: {self.price}, authorName: {self.authorName}')
# Regular method 2
def get_author_info(self):
print(f'The author name: {self.authorName}, born : {self.authorBorne}')
# creating an instance/object of the storyBook class
book1 = StoryBook('hamlet', 350, 'Shakespeare', 1564, 500)
book2 = StoryBook('The knite runner', 200, 'khalid hossini', 1965, 230)
book1.get_book_info()
book2.get_author_info()
print(book1.name)
print(book2.name)
print(book1.publishingYear)
print(book2.no_of_pages)
| true |
752cd493edac4ad35a04b1ce29c7b9449fe6d797 | tarabrosnan/hearmecode | /lesson04/lesson04_events_deduplicate.py | 986 | 4.125 | 4 | # Challenge level: Beginner
# Scenario: You have two files containing a list of email addresses of people who attended your events.
# File 1: People who attended your Film Screening event
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt
#
# File 2: People who attended your Happy hour
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/happy_hour_attendees.txt
#
# Note: You should create functions to accomplish your goals.
# Goal 1: You want to get a de-duplicated list of all of the people who have come to your events.
def deduplicate(file1, file2):
with open(file1, 'r') as file1:
file1_contents = file1.read().split('\n')
with open(file2, 'r') as file2:
file2_contents = file2.read().split('\n')
dedupe = list(set(file1_contents+file2_contents))
return dedupe
print deduplicate("film_screening_attendees.txt", "happy_hour_attendees.txt")
| true |
3b50e9eb168075eb3aea43d8a75418171b5347c2 | HenriqueCostaSI/Python | /reversed.py | 908 | 4.59375 | 5 | """
Reversed-> Inverter o Interável
Obs: Não confunda com reverse() de listas
A função retorna um List Reverse Iterator
"""
# Exemplos
lista = [1, 2, 3, 4, 5]
res = reversed(lista)
# Lista
print(list(reversed(lista)))
# Tupla
print(tuple(reversed(lista)))
# Conjunto
print(set(reversed(lista))) # Em conjunto nós não guardamos ordem inv
################################
# Podemos interar sobre o reversed
for letra in reversed("Geek University"):
print(letra, end='')
# Podemos fazer o mesmo sem o forma
print(''.join(list(reversed("Geek University"))))
# Já Vimos como fazer isso mais fácil com o slice de strings
print('Geek University'[::-1])
# Podemos também utilizar o reversed() para fazer um loop for reverso
for n in reversed(range(0, 10)):
print(n)
# Apesar que também já vimos como fazer isso utilizando o próprio range()
for n in range(9, -1, -1):
print(n)
| false |
aae91a00e84efddf7be4fdb7194b73e9a4d0100f | HenriqueCostaSI/Python | /modulo_random.py | 2,681 | 4.125 | 4 | """
Módulo Random e o que são módulos?
- Em Python, módulos são outros arquivos Python.
Módulo Random -> Possui várias funções para geração de números pseudo-aleatório.
"""
# OBS: Existem duas formas de se utilizar um módulo ou função desempacotamento
# Forma 1 - Importando todo o módulo (Não recomendado).
from random import choice
import random import radiant
from random import uniform
from random import random
import random
# random()-> Gera um número pseudo-aleatório entre 0 e 1.
# OBS: Ao realizar o import de todo módulo, todas as funções, atributos, classes e propriedades que estiverem
# dentro do módulo dicarão disponíveis (Ficarão em Memória). Caso você saiba quais funções você precisa utilizar
# desde módulo, então esta não seria a forma ideal de utilização. Nós veremos uma forma melhor na Forma 2.
print(random.random())
# Veja que para utilizar a função random() do pacote random, nós colocamos o nome do pacote e o nome da função, separados por ponto.
# OBS: Não confunda a função random() com o pacote random. Pode parecer confuso, mas a função random é
# apenas uma função dentro do módulo random.
########################################################################################################################################
# Forma 2 - Importando uma função específica do módulo
# No import acima, estamos falando: Do módulo random, importe a função random
for i in range(10):
print(random())
########################################################################################################################################
# uniform() -> Gerar um número real pseudo-aleatório entra os valores estabelecidos
for i in range(10):
print(uniform(3, 7)) # 7 não é incluído
########################################################################################################################################
# radiant() -> Gera valores inteiros pseudo-aleatório
# Gerador de apostas para mega_sena
for i in range(6):
print(radiant(1, 61), end=', ') # começa em 1 e vai até 60
########################################################################################################################################
# choice() -> Mostra um valor aleatório entre um iterável
jogadas = ['pedra', 'papel', 'tesoura']
print(choice(jogadas))
########################################################################################################################################
# shuffle() -> Tem a função de embaralhar Dados
cartas = ['k', 'q', 'j', 'a', '2', '3', '4', '5', '6', '7']
print(shuffle(cartas))
print(cartas.pop())
| false |
fdad87ebcc7a3644e7715817fead3af699d47543 | HenriqueCostaSI/Python | /Ordered_dict.py | 605 | 4.1875 | 4 |
"""
Ordered Dict
# Em um dicionário a ordem de inderção dos elemtos não é garantida
dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
for chave, valor in dict.items():
print(f'chave={chave}:valor={valor}')
"""
# Importando
from collections import OrderedDict
dic = orderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6})
# Entendo as Diferenças
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'c': 3, 'b': 2}
print(dict1 == dict2) # Deu True
odict1 = OrderedDict({'a': 1, 'b': 2, 'c': 3})
odict2 = OrderedDict({'a': 1, 'c': 3, 'b': 2})
print(odict1 == odict2) # Deu False
| false |
5cdfa102cff1c3210258e57c45eb8ba103e90481 | RodiMd/Python | /RomanNumeralsRange.py | 1,937 | 4.125 | 4 | #Roman Numerals
#prompt user to enter a value between 1 and 10.
number = input('Enter a number between 1 and 10 ')
number = float(number)
def main():
if number == 1:
print('The value entered ', number, 'has a roman equivalent of I')
else:
if number == 2:
print('The value entered ', number, 'has a roman equivalent of II')
else:
if number == 3:
print('The value entered ', number, 'has a roman equivalent of III')
else:
if number == 4:
print('The value entered ', number, 'has a roman equivalent of IV ')
else:
if number == 5:
print('The value entered ', number, 'has a roman equivalent of V ')
else:
if number == 6:
print('The value entered ', number, 'has a roman equivalent of VI')
else:
if number == 7:
print('The value entered ', number, 'has a roman equivalent of VII')
else:
if number == 8:
print('The value entered ', number, 'has a roman equivalent of VIII')
else:
if number == 9:
print('The value entered ', number, 'has a roman equivalent of IX')
else:
if number == 10:
print('The value entered ', number, 'has a roman equivalent of X')
else:
print('Error: The value entered ', number, 'is outside the specified range')
main()
| true |
19d948529b4da0ca728c55653e413629487b606f | RodiMd/Python | /MonthlyCarCost.py | 690 | 4.1875 | 4 | #Automobile Costs
#ask user to input automobile costs including: loan payment
#insurance, gas, oil, tires, maintenance.
loanPayment = input('Enter auto monthly payment ')
insurance = input('Enter insurance cost ')
gas = input('Enter monthly gas cost ')
oil = input('Enter monthly oil cost ')
tires = input('Enter montly tires cost ')
maintenance = input('Enter monthly maintenance cost ')
oil = (1.0 / 3.0) * float(oil)
tires = (1.0 / 24.0) * float(tires)
def main():
totalMonthlyCost = float(loanPayment) + float(insurance) + float(gas) + float(oil) + float(tires)
+ float(maintenance)
print ('Total monthly cost of a car %.2f ' %totalMonthlyCost)
main()
| true |
19be8d9e73b668b2039865214c3bb7b1937c1924 | RodiMd/Python | /convertKmToMiles.py | 383 | 4.4375 | 4 | #Kilometer Converter
#write a program that converts km to mi
#ask the user to enter a distance in km
distanceKilometers = input('Enter a distance in km ')
distanceKilometers = float(distanceKilometers)
def conversionTokilometers():
miles = distanceKilometers * 0.6214
print ('The distance entered in kilometers is %.2f' %miles, 'miles')
conversionTokilometers()
| true |
012f04a108ad5bb0d1d6a2a939389d9ed6ba9736 | devprofe/python | /ej1_clases2406.py | 433 | 4.125 | 4 | #DECLARAR UNA LISTA VACIA
numeros = []
#COMO LLENAR UNA LISTA SOLO CON APPEND
#numeros.append(35)
#numeros.append(28)
#numeros.append(12)
#INGRESAR NUMEROS EN UNA LISTA MEDIANTE INSERT Y FOR.
#for i in range(5):
#numeros.insert(i, float(input("ingrese numero:")))
#INGRESAR NUMEROS EN UNA LISTA MEDIANTE APPEND Y FOR.
for i in range(3):
numeros.append(float(input("Ingrese Numeros:")))
#VISUALIZAR LA LISTA
print(numeros)
| false |
66079189a84d8cd1c08a3b9eee964f6a116395d4 | h8rsha/tip-calculator | /main.py | 441 | 4.125 | 4 | if __name__ == '__main__':
print("Welcome to the tip calculator.")
total_bill = input("What was the total bill? ")
tip_percentage = input("What percentage tip would you like to give? 10, 12 or 15? ")
people_count = input("How many people to split the bill? ")
total_amount = (float(total_bill) / int(people_count)) * (1 + 0.01 * float(tip_percentage))
print(f"Each person should pay : ${round(total_amount, 2)}")
| true |
b5e6f4348b9445639f2696caac83c9a761200cc0 | zchiam002/vecmc_codes_zhonglin | /nsga_ii/nsga_ii_para_imple_evaluate_objective.py | 2,310 | 4.15625 | 4 | ##Function to evaluate the objective functions for the given input vector x. x is an array of decision variables
##and f(1), f(2), etc are the objective functions. The algorithm always minimizes the objective function hence if
##you would like to maximize the function then multiply the function by negative one.
def nsga_ii_para_imple_evaluate_objective (variable_values, num_obj_func, iteration_number):
##variable_values --- the array of variable values to be evaluated
##num_obj_func --- the nuber of objective functions to evaluate
##iteration_number --- a unique number so that saving the file name will be unique
import numpy as np
##Creating a numpy array to store the objective function values
objective_values = np.zeros((1, num_obj_func))
##Iterating based on the number of objective functions to be evaluated
for i in range (0, num_obj_func):
objective_values[0,i] = kursawe_function_moo (variable_values, i)
return objective_values
######################################################################################################################################################################################
##Test functions
##This is the kursawe test function
## -5 <= x_i <= 5
## 1 <= i <= 3
## num_obj_func = 2
def kursawe_function_moo (x, obj_to_evaluate):
##x --- the list of variable values
##obj_to_evaluate --- the objective function to evaluate
import math
##Determining the number of variables to be evaluated
num_var = len(x)
##Determining which objective function to evaluate
if obj_to_evaluate == 0:
ret_obj = 0
for i in range (0, num_var-1):
v1 = x[i]
v2 = x[i+1]
ret_obj = ret_obj + (-10 * math.exp(-0.2 * math.sqrt(pow(v1, 2) + pow(v2, 2))))
elif obj_to_evaluate == 1:
ret_obj = 0
for i in range (0, num_var):
v1 = x[i]
if v1 < 0:
ret_obj = ret_obj + (pow(-v1, 0.8) + (5 * math.sin(pow(v1, 3))))
else:
ret_obj = ret_obj + (pow(v1, 0.8) + (5 * math.sin(pow(v1, 3))))
return ret_obj
| true |
5e4e2fdc4c1037667821e5f23ad88ccc62f7de18 | Salcazul/ComputerElective | /Quiz2.py | 622 | 4.21875 | 4 | #Name
name = raw_input("What is your name?")
#Last Name
last = raw_input("What is your last name?")
#Class
classname = raw_input("What class are you in?")
#Year of birth
year = input("What is your year of birth?")
#Calculate current age
age = 2015 - year
print "You are", age, "years of age."
#Computer grade 1S
s1 = input("What is your first semester grade?")
#Computer grade 2S
s2 = input("What is your second semester grade?")
#Calculate final grade
final = (s1 + s2) / 2
#Print in a string name, lastname, class, final grade
print "Your name is", name, last+". Your final grade in", classname, "is", final, "."
| true |
ed218f5025544474394bed9e161c987edd884a3e | yk2684/Codewars | /7kyu/Highest-and-Lowest.py | 410 | 4.125 | 4 | #In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
#Example:
#high_and_low("1 2 3 4 5") # return "5 1"
#high_and_low("1 2 -3 4 5") # return "5 -3"
#high_and_low("1 9 3 4 -5") # return "9 -5"
def high_and_low(numbers):
num_list = sorted([int(n) for n in numbers.split(' ')])
return "{} {}".format(num_list[-1], num_list[0]) | true |
89074f4afad000944e11ed9fcc508ecc69e42233 | yk2684/Codewars | /8kyu/Return-negative.py | 435 | 4.65625 | 5 | #In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
#Example:
#make_negative(1); # return -1
#make_negative(-5); # return -5
#make_negative(0); # return 0
#Notes:
#The number can be negative already, in which case no change is required.
#Zero (0) can't be negative, see examples above.
def make_negative( number ):
return number if number <= 0 else -number | true |
c4d957205efb049acc46b4cc892ef0fb32b8607f | Abdulkadir78/Python-basics | /q16.py | 690 | 4.34375 | 4 | '''
Use a list comprehension to square each odd number in a list.
The list is input by a sequence of comma-separated numbers.
Suppose the following input is supplied to the program:
1, 2, 3, 4, 5, 6, 7, 8, 9
Then, the output should be:
1, 9, 25, 49, 81
'''
numbers = input('Enter comma separated sequence of numbers: ')
temp_list = numbers.split(',')
l = []
final_list = [] # this list is used just for converting the integer list 'l' to a comma separated string
for number in temp_list:
if int(number) % 2 != 0:
l.append(int(number) ** 2)
for number in l:
# converting integer list 'l' to a string list
final_list.append(str(number))
print(', '.join(final_list))
| true |
278c75115f7d16cbb3b881b0ea0ec90d22eca62a | Abdulkadir78/Python-basics | /q7.py | 565 | 4.21875 | 4 | '''
Write a program which takes 2 digits, X, Y as input and generates
a 2-dimensional array. The element value in the i-th row and j-th
column of the array should be i*j.
Example
Suppose the following inputs are given to the program:
3, 5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
'''
dimensions = input('Enter X,Y: ')
l = dimensions.split(',')
rows = int(l[0])
columns = int((l[1]))
l2 = []
for i in range(rows):
l3 = []
for j in range(columns):
l3.append(i * j)
l2.append(l3)
print(l2)
| true |
f28b75916667124438f2c9e661078cf25ac70277 | Abdulkadir78/Python-basics | /q35.py | 663 | 4.15625 | 4 | '''
Please write a program which counts and prints the numbers of
each character in a string input by console.
Example:
If the following string is given as input to the program:
abcdefgabc
Then, the output of the program should be:
a, 2
b, 2
c, 2
d, 1
e, 1
f, 1
g, 1
'''
string = input('Enter a string: ')
l = []
for character in string:
if character not in l:
l.append(character)
print(f'{character}, {string.count(character)}')
'''
ALTERNATE SOLUTION:
dic = {}
string = input('Enter a string: ')
for character in string:
dic[character] = dic.get(character, 0) + 1
print('\n'.join(['%s, %s' % (k, v) for k, v in dic.items()]))
'''
| true |
911f65f6917f1b17ebc6cb8c325e650549fe2bc3 | sapphacs13/python_basics | /syntax/functions.py | 722 | 4.125 | 4 | # Python uses white space. Everything you define or use has
# to have the correct indentation.
def adder(a, b):
return a + b
print adder(1, 2) # runs adder(1,2) and prints it (should print 3)
def subtracter(a, b):
return a - b
print subtracter(3, 2) # runs the subtracter and prints (should print 1)
# lets talk about the difference between print and return
def adder2(a, b):
print a + b
adder2(1, 2) # prints 3.
# Notice how we dont need to print this we only need to call it.
# The downside is that we cannot save a variable like a = adder2(4, 5).
# This is because the function only prints, it does not save anything.
# Looking at the first adder function however:
a = adder(4, 5)
print a
# prints 9
| true |
5e99a7b51a52f5301a2cb3bc65f019d52051982e | bigcat2014/Cloud_Computing | /Assignment 2/step2.py | 615 | 4.21875 | 4 | #!/usr/bin/python3
#
# Logan Thomas
# Cloud Computing Lab
# Assignment 2
#
# Capitalize the first letter of each word in the string and
# take the sum of all numbers, not contained in a word, and
# print the new string and the sum.
def main():
total = 0.0
user_input = input("Please enter a string\n>> ")
user_input = user_input.split()
output = []
for word in user_input:
try:
total += float(word)
output.append(word)
except ValueError:
output.append(word.capitalize())
output = ' '.join(output)
print('"%s", the sum of numbers is %.3f' % (output, total))
if __name__ == "__main__":
main() | true |
028f52f7e8a2633ba868029ca06263e993e9ca20 | bigcat2014/Cloud_Computing | /Assignment 2/shape.py | 889 | 4.125 | 4 | #!/usr/bin/python3
#
# Logan Thomas
# Cloud Computing Lab
# Assignment 2
#
from math import sqrt
class Shape:
sides = []
name = ''
def __init__(self):
self.name = 'Shape'
def area(self):
pass
class Rectangle(Shape):
def __init__(self, x, y):
super().__init__()
self.name = 'Rectangle'
self.sides = [x, y]
def area(self):
return self.sides[0] * self.sides[1]
class Triangle(Shape):
def __init__(self, s1, s2, s3):
super().__init__()
self.name = 'Triangle'
self.sides = [s1, s2, s3]
def area(self):
p = (self.sides[0] + self.sides[1] + self.sides[2]) / 2
return sqrt(p * (p - self.sides[0]) * (p - self.sides[1]) * (p - self.sides[2]))
def get_shape(line):
line = line.split()
shape_type = line[0]
if shape_type == 'T':
return Triangle(float(line[1]), float(line[2]), float(line[3]))
else:
return Rectangle(float(line[1]), float(line[2]))
| false |
1d92d87875f37503b14413d484e8656e426ac5d1 | JoelBrice/PythonForEveryone | /ex3_03.py | 439 | 4.21875 | 4 | """Check that the score is between the range and display the score level according to the score"""
score = input("Enter Score: ")
s = 0.0
try:
s = float(score)
except:
print("Error out of range!")
if s >=0 and s<=1:
if s>= 0.9:
print("A")
elif s >=0.8:
print("B")
elif s>=0.7:
print("C")
elif s>=0.6:
print("D")
elif s<0.6:
print("F")
else:
print("Out of range")
| true |
270c5c788c1fdad02806b75d3e693ef7de6c1974 | paty0504/nguyentienthanh-fundamental-c4e13 | /ss5/dict1.py | 445 | 4.1875 | 4 | dic = {
"eny" : "Em người yêu",
"any" : "Anh người yêu",
"cl" : "con lợn",
"hc" : "học",
"ik" : "đi",
}
while True:
search = input('Your code: ')
if search in dic:
print(dic[search])
else:
print('Not found')
choice = input(' Would you like to update? Y or N?:').lower()
if choice == 'y':
dic[search] = input('Meaning: ')
print(dic)
else:
break
| false |
bcc25fa4698e6c2e3d8bdef4290d8cdbc90bc7bc | alberico04/Test | /main.py | 2,845 | 4.25 | 4 | #### Describe each datatype below:(4 marks)
## 4 = integer
## 5.7 = float
## True = boolean
## Good Luck = string
#### Which datatype would be useful for storing someone's height? (1 mark)
## Answer: FLOAT
#### Which datatype would be useful for storing someone's hair colour?(1 mark)
## Answer: STRING
####Create a variable tha will store the users name.(1 mark)
name=input("Enter your name: ")
####Create a print statement that will print the first 4 characters of the person's name.(3 marks)
print(name[0:4])
####Convert the user's name to all uppercase characters and print the result
name=name.upper()
print(name)
####Find out how many times the letter A occurs in the user's name
print(name.count("A"))
#### Create a conditional statement to ask a user to enter their age. If they are older than 18 they receive a message saying they can enter the competition, if they are under 18, they receive a message saying they cannot enter the competition.
age=int(input("enter your age:"))
if age > 18:
print("You can join the competition")
else:
print("You can not enter the competition")
#### Create an empty list called squareNumbers (3 marks)
squareNumbers=[]
#### Square numbers are the solutions to a number being multiplied by itself( example 1 is a square number because 1 X 1 = 1, 4 is a square number because 2 X 2 = 4 ).
###Calculate the first 20 square numbers and put them in the list called squareNumbers. (With loop and .append 10 marks, without, Max 6 marks).
squareNumbers.append(1)
squareNumbers.append(2*2)
squareNumbers.append(3*3)
squareNumbers.append(4*4)
squareNumbers.append(5*5)
squareNumbers.append(6*6)
squareNumbers.append(7*7)
squareNumbers.append(8*8)
squareNumbers.append(9*9)
squareNumbers.append(10*10)
squareNumbers.append(11*11)
squareNumbers.append(12*12)
squareNumbers.append(13*13)
squareNumbers.append(14*14)
squareNumbers.append(15*15)
squareNumbers.append(16*16)
squareNumbers.append(17*17)
squareNumbers.append(18*18)
squareNumbers.append(19*19)
squareNumbers.append(20*20)
####Print your list (1 mark)
print(squareNumbers)
####Create a variable called userSquare that asks the user for their favourite square number
userSquare=int(input("Enter your favourite square number: "))
#### Add this variable to the end of your list called SquareNumbers
squareNumbers.append(userSquare)
print(squareNumbers)
### Create a variable called choice. This variable should choose a random element from your list. Print the variable called choice.(3 marks)
import random
choice=squareNumbers[random.randint(0,20)]
if choice in squareNumbers:
print(choice)
####Create another print statement that prints tha following output: The random square number is: XX, where XX is where the random square number chosen by the computer.(4 marks)
print("The random square number is",choice) | true |
82575d812269b58cb220e0e5c9218d5e9f5d4d11 | christophercalle/Tues_Sept_18 | /calculator.py | 581 | 4.21875 | 4 | def add(num1,num2):
print(num1 + num2)
def subtract(num1,num2):
print(num1 - num2)
def multiply(num1,num2):
print(num1 * num2)
def divide(num1,num2):
print(num1 / num2)
first_number = int(input("Give me a number: "))
operator = input("Give me a math operator: ")
second_number = int(input("Give me another number: "))
if operator == "+":
add(first_number,second_number)
if operator == "-":
subtract(first_number,second_number)
if operator == "*":
multiply(first_number,second_number)
if operator == "/":
divide(first_number,second_number)
| false |
4cb82d079ffac6a7d07d598ab27ebb14d840f9b7 | abhilash1392/pythonBasicExercisesPart1 | /exercise_5.py | 292 | 4.25 | 4 | """5. Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them."""
first_name=input('Please enter your first name: ')
last_name=input('Please enter your last name: ')
print('Hello {} {}'.format(last_name,first_name))
| true |
a2929fd09d1daf91b1b4e2b08446820d38f75d67 | aleksandramitula/PYTHON_ola | /Dzien3/dzien3.py | 1,108 | 4.125 | 4 | temperature = input("Podaj temperature: ")
#DUZYMI LITERAMI piszemy stala, nie zmienna. To sa te wartosci, ktorych nie chcemy zmieniac w srodku w kodzie, ale mozna zmienic na poczatku:
HOT_TEMPERATURE=30
WARM_TEMPERATURE=25
NOT_COLD_NOT_WARM_TEMPERATURE=20
if temperature >=HOT_TEMPERATURE:
print("it's hot")
elif temperature >=WARM_TEMPERATURE:
print("it's warm")
elif temperature >=NOT_COLD_NOT_WARM_TEMPERATURE:
print("it's not warm or cold")
else:
print("it's cold")
# napisz program:
# jezeli slowo zaczyna sie na a - napisz "zaczyna sie na 1 litere alfabetu", jezeli z - zaczyna sie na ostatnia, jezeli inaczej - zaczyna sie na inna litere alfabetu
slowo=input("Podaj slowo: ")
if slowo[0]=='a':
print("Slowo zaczyna sie na pierwsza litere alfabetu")
elif slowo[0]=='z':
print("Slowo zaczyna sie na ostatnia litere alfabetu")
else:
print("Slowo zaczyna sie na inna litere alfabetu niz 'a' lub 'z'")
# lista zagniezdzona
lista=[[1,2,3],[4,5,6],[7,8,9]]
print(lista[1][2])
#wynik = 6 (z drugiej listy trzeci element)
print(lista[1:])
#wynik = [[4, 5, 6], [7, 8, 9]] | false |
e4975175bb97edd715411f62c8a168dfe32570eb | nbrahman/HackerRank | /03 10 Days of Statistics/Day08-01-Least-Square-Regression-Line.py | 1,450 | 4.21875 | 4 | '''
Objective
In this challenge, we practice using linear regression techniques. Check out the Tutorial tab for learning materials!
Task
A group of five students enrolls in Statistics immediately after taking a Math aptitude test. Each student's Math aptitude test score, x, and Statistics course grade, y, can be expressed as the following list of (x,y) points:
1. (95,85)
2. (85,95)
3. (80,70)
4. (70,65)
5. (60,70)
If a student scored 80 an on the Math aptitude test, what grade would we expect them to achieve in Statistics? Determine the equation of the best-fit line using the least squares method, then compute and print the value of y when x=80.
Input Format
There are five lines of input; each line contains two space-separated integers describing a student's respective x and y grades:
95 85
85 95
80 70
70 65
60 70
If you do not wish to read this information from stdin, you can hard-code it into your program.
Output Format
Print a single line denoting the answer, rounded to a scale of 3 decimal places (i.e., 1.234 format).
'''
# import library
import statistics as st
# Set data
n = 5
x = [95, 85, 80, 70, 60]
y = [85, 95, 70, 65, 70]
meanX = st.mean(x)
meanY = st.mean(y)
x_s = sum([x[i] ** 2 for i in range(5)])
xy = sum([x[i]*y[i] for i in range(5)])
# Set the B and A
b = (n * xy - sum(x) * sum(y)) / (n * x_s - (sum(x) ** 2))
a = meanY - b * meanX
# Gets the result and show on the screen
print (round(a + 80 * b, 3)) | true |
7d1e10a0303d71f3ff95a22bf44e2963b3745f22 | nbrahman/HackerRank | /01 Algorithms/01 Warmup/TimeConversion.py | 969 | 4.25 | 4 | '''
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Input Format
A single string containing a time in 12-hour clock format (i.e.: hh:mm:ss AM or hh:mm:ss PM ), where 01 <= hh <= 12 and 00 <= mm,ss <= 59.
Output Format
Convert and print the given time in 24-hour format, where 00 <= hh <= 23.
Sample Input
07:05:45PM
Sample Output
19:05:45
'''
if __name__ == '__main__':
time = input().strip()
arr = time.split(":")
print ('{:02d}'.format(int(arr[0])%12 + (0 if arr[2][len(arr[
2])-2:]=="AM" else
12))+":"'{:02d}'.format(int(arr[
1]))+":"+'{:02d}'.format(int(arr[2][
0:2])))
| true |
fd4be7ead12bb78ac455902f0721c2655643d7f4 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Utopian-Tree.py | 1,421 | 4.21875 | 4 | '''
The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.
Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T subsequent lines each contain an integer, N, denoting the number of cycles for that test case.
Constraints
1<=T<=10
0<=N<=60
Output Format
For each test case, print the height of the Utopian Tree after N cycles. Each height must be printed on a new line.
Sample Input
3
0
1
4
Sample Output
1
2
7
Explanation
There are 3 test cases.
In the first case (N=0), the initial height (H=1) of the tree remains unchanged.
In the second case (N=1), the tree doubles in height and is 2 meters tall after the spring cycle.
In the third case (N=4), the tree doubles its height in spring (H=2), then grows a meter in summer (H=3), then doubles after the next spring (H=6), and grows another meter after summer (H=7). Thus, at the end of 4 cycles, its height is 7 meters.
'''
#!/bin/python3
import sys
def calculateUtopianTreeHeight (t,n):
h = 1
for i in range(0,n-1,2):
h=(h*2)+1
if n>0 and n%2==1:
h*=2
print(h)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
calculateUtopianTreeHeight(t,n) | true |
13c10b8411890edb52c47de0543427793125cd55 | nbrahman/HackerRank | /01 Algorithms/02 Implementation/Circular-Array-Rotation.py | 1,807 | 4.28125 | 4 | '''
John Watson performs an operation called a right circular rotation on an array of integers, [a0, a1, a2, an-1]. After performing one right circular rotation operation, the array is transformed from [a0, a1,
a2, an-1] to [an-1, a0, a1, a2, an-2].
Watson performs this operation k times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks q queries, where each query consists of a single integer, m, for which you must print the element at index m in the rotated array (i.e., the value of am).
Input Format
The first line contains 3 space-separated integers, n, k, and q, respectively.
The second line contains n space-separated integers, where each integer i
describes array element ai (where 0 <= i <= n).
Each of the subsequent lines contains a single integer denoting m.
Constraints
1 <= n <= 10^5
1 <= ai <= 10^5
1 <= k <= 10^5
1 <= q <= 500
0 <= m <= n-1
Output Format
For each query, print the value of the element at index m of the rotated
array on a new line.
Sample Input 0
3 2 3
1 2 3
0
1
2
Sample Output 0
2
3
1
Explanation 0
After the first rotation, the array becomes [3,1,2].
After the second (and final) rotation, the array becomes [2, 3, 1].
Let's refer to the array's final state as array b. For each query, we just
have to print the value of bm on a new line:
m = 0, so we print 2 on a new line.
m = 1, so we print 3 on a new line.
m = 2, so we print 1 on a new line.
'''
if __name__ == '__main__':
n, k, q = input().strip().split(' ')
n, k, q = [int(n), int(k), int(q)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
b = []
for a0 in range(q):
m = int(input().strip())
b.append (m)
print ('Output')
for i in b:
print(a[(i-k)%len(a)]) | true |
5d0df4565c0a9c8ddd4442a609050631ae3310f9 | kumarchandan/Data-Structures-Python | /3-linked_lists/c6_detect_loop_in_linked_list/main-floyd-algo.py | 1,201 | 4.125 | 4 | '''
This is perhaps the fastest algorithm for detecting a linked list loop. We keep
track of two iterators, onestep and twostep.
onestep moves forward one node at a time, while twostep iterates over two nodes. In this way,
twostep is the faster iterator.
By principle, if a loop exists, the two iterators will meet. Whenever this condition is
fulfilled, the function returns True.
'''
from LinkedList import LinkedList
# Floyd's Cycle Finding Algorithm
def detect_loop(lst): # O(n)
# Keep two iterators
onestep = lst.get_head()
twostep = lst.get_head()
while onestep and twostep and twostep.next_element: # O(n)
onestep = onestep.next_element # Moves one node at a time
twostep = twostep.next_element.next_element # Skips a node
if onestep == twostep: # Loop exists
return True
return False
# ----------------------
lst = LinkedList()
lst.insert_at_head(21)
lst.insert_at_head(14)
lst.insert_at_head(7)
# Adding a loop
head = lst.get_head()
node = lst.get_head()
for i in range(4):
if node.next_element is None:
node.next_element = head.next_element
break
node = node.next_element
print(detect_loop(lst))
| true |
6fb12a06b85202ca2e2e90d5baf5d198727d7cf0 | Unrealplace/Python | /Python基础教程/loop.py | 395 | 4.34375 | 4 | # 循环的使用
namelist = ['fanyangyang','yangyangfan','oliverlee']
nametuple = ('hello','world','nice ','to','meet you')
# Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来,看例子:
for name in namelist:
print(name)
pass
for item in nametuple:
print(item)
pass
#遍历索引的方式
for x in range(1,10):
print(x)
pass | false |
9985b32d8d79fb4bfde8d0ffbec712e5b88ac8d4 | gomanish/Python | /Linked_List/add_and_delete_last_node.py | 910 | 4.25 | 4 | # Add and Delete Last Node in a linked list
class Node:
def __init__(self,val):
self.value = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def printallnodeval(llist):
temp=llist.head
while temp:
print temp.value
temp=temp.next
return
def DeleteNode(head):
temp=head
while temp.next.next:
temp=temp.next
temp.next=None
return head
def InserteNode(head,tail,value):
temp=Node(value)
tail.next=temp
return head
# Creating Node
a=Node(1)
b=Node(2)
c=Node(3)
d=Node(4)
e=Node(5)
a.next = b
b.next = c
c.next = d
d.next = e
llist=LinkedList()
llist.head = a
llist.tail = e
printallnodeval(llist)
print 'after addition of Node'
llist.head=InserteNode(llist.head,llist.tail,10)
printallnodeval(llist)
print 'Delete Node from tail of the linked list'
llist.tail=DeleteNode(llist.head)
printallnodeval(llist)
| true |
eae27424746c9423d92b345429cf1acb5d5656e9 | gomanish/Python | /basic/threesquares.py | 348 | 4.1875 | 4 | '''Write a Python function threesquares(m) that takes an integer m as input and returns True.
if m can be expressed as the sum of three squares and False otherwise.
(If m is not positive, your function should return False.)'''
def threesquares(n):
if n<0:
return False
while(n%4==0):
n=n/4
n=n-7
if(n%8==0):
return False
return True
| true |
39bcbe9d664219f56608744cc6e2b0e88261fa2a | carriehe7/bootcamp | /IfStatementBasics.py | 1,118 | 4.125 | 4 | # if statements basics part 1
salary = 8000
if salary < 5000:
print('my salary is too low, need to change my job')
else:
print('salary is above 5000, okay for now')
age = 30
if age > 50:
print('you are above 50. you are a senior developer for sure')
elif age > 40:
print('your age is bigger than 40. you are a developer for some time, but if not, better late than never')
elif age > 35:
print('so you are more than 35yo, I might guess you are a developer')
else:
print("doesn't matter what age you are. let's code python")
# if statements basic part 2
age = 30
name = 'James'
# logical operator - 'and'
if age > 20 and name == 'James':
print('my name is James and I am over 20')
else:
print('default exit point')
# logical operator - 'or'
if age > 20 or name == 'James':
print('my name is James and I am over 20')
else:
print('default exit point')
# nested 'if' statement
married = True
if age > 20 and name == 'James':
if married == True:
print("good luck, it's gonna be a long happy ride")
else:
print('nested else')
else:
print('parent else') | true |
e180350b63cc478a403a3df45cc5e781d70c5d5f | carriehe7/bootcamp | /TupleCollectionHW.py | 1,642 | 4.5625 | 5 | # 1. Create a ‘technological_terms’ tuple that will contain the following items:
# a. python
# b. pycharm IDE
# c. tuple
# d. collections
# e. string
technological_terms = ('python', 'pycharm IDE', 'tuple', 'collections', 'string')
print('technological terms tuple collection : ' +str(technological_terms))
# 2. Print the following sentence using cell extraction to the needed cells:
# “We are ninja developers. We write python code in pycharm IDE, and now practicing tuple collections topic, that contains string variables.”
# Instructions:
# a. Words marked in purple - usual extraction of cell by index
# b. Words marked in yellow - extraction by negative cell index
print('print sentence with cell extraction: We are ninja developers. We write ' +(technological_terms[0])
+' code in ' +(technological_terms[-4])
+', and now practicing ' +(technological_terms[2])
+' collections topic, that contains ' +(technological_terms[-1]) +' variables.')
# 3. Insert the variables “float” and “list” into the tuple. Add them to the end of the collection
# (Hint : We studied how to add new cells on ‘list - advanced’ lecture)
technological_terms_list = list(technological_terms)
technological_terms_list.append('float')
technological_terms_list.append('list')
technological_terms = tuple(technological_terms_list)
print('add variables to collection : ' +str(technological_terms))
# 4. Create a single cell tuple with the number ‘1’ in it. Also, print out the ‘type’ of the data collection
single_cell_tuple = (1,)
print('single cell tuple : ' +str(single_cell_tuple))
print(type(single_cell_tuple))
| true |
572eb584fb562b811de2b73c517ed4fffbf5c8e2 | mbonnemaison/Learning-Python | /First_programs/boolean_1.py | 730 | 4.15625 | 4 | """
def list_all(booleans):
Return True if every item in the list is True; otherwise return False
list_all([]) = True
list_all([True]) = True
list_all([False]) = False
list_all([True, False, True]) = False
raise Exception("TODO")
"""
def list_all(booleans):
for bools in booleans:
if not isinstance(bools, bool):
raise TypeError("expected bool, got {}".format(type(bools)))
if False not in booleans:
print(True)
else:
print(False)
#Examples to test the code above:
list_all_test_cases = [[], [True], [False], [True, False, True], [True, True], ["Matt", "Mathilde"], [23, 4.3]]
for x in list_all_test_cases:
try:
list_all(x)
except TypeError as e:
print(e)
| true |
2205eee999f0175dbb14cc40d239bd819fc83baa | KarenAByrne/Python-ProblemsSets | /fib.py | 1,159 | 4.21875 | 4 | # Karen Byrne
# A program that displays Fibonacci numbers.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# Test the function with the following value. My name is Karen , so the first and last letter of my name (K+ N = 11 + 14)
# give the number 25. The 25th Fibonacci number is 75025.
# Fibonacci number 25 is 75025
# I had some issues. I followed the helpful thread so thanks to all contributors.
x = 25
ans = fib(x)
print("Fibonacci number", x, "is", ans)
# Karen Byrne
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Byrne"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
| true |
c8cd572bde563d3cebd748dde843402cd1fb2077 | camaral82/Python_Self_Study_MOSH | /Dictionary.py | 506 | 4.28125 | 4 | """24/09/2020 - Thursday
Dictionary Exercise
Type a sequence of numbers and at the end
transcript each element.
In case of typing a character, show ! """
digits_mapping = {"1": "One", "2": "Two", "3": "Three",
"4": "Four", "5": "Five", "6": "Six",
"7": "Seven", "8": "Eight", "9": "Nine",
"0": "Zero"}
digits = input("Type your phone number: ")
output = ""
for ch in digits:
output += digits_mapping.get(ch, "!") + " "
print(output) | true |
72663f0656ad734acee538dc6aa8f8d67256d49a | saileshkhadka/SearchingAlgorithm-in-Python | /LargestElementfromlistinLinearTime.py | 2,475 | 4.1875 | 4 | # Problem Description
# The program takes a list and i as input and prints the ith largest element in the list.
# Problem Solution
# 1. Create a function select which takes a list and variables start, end, i as arguments.
# 2. The function will return the ith largest element in the range alist[start… end – 1].
# 3. The base case consists of checking whether there is only one element in the list and if so, alist[start] is returned.
# 4. Otherwise, the list is partitioned using Hoare’s partitioning scheme.
# 5. If i is equal to the number of elements in alist[pivot… end – 1], call it k, then the pivot is the ith largest element.
# 6. Otherwise, depending on whether i is greater or smaller than k, select is called on the appropriate half of the list.
# Program/Source Code
def select(alist, start, end, i):
"""Find ith largest element in alist[start... end-1]."""
if end - start <= 1:
return alist[start]
pivot = partition(alist, start, end)
# number of elements in alist[pivot... end - 1]
k = end - pivot
if i < k:
return select(alist, pivot + 1, end, i)
elif i > k:
return select(alist, start, pivot, i - k)
return alist[pivot]
def partition(alist, start, end):
pivot = alist[start]
i = start + 1
j = end - 1
while True:
while (i <= j and alist[i] <= pivot):
i = i + 1
while (i <= j and alist[j] >= pivot):
j = j - 1
if i <= j:
alist[i], alist[j] = alist[j], alist[i]
else:
alist[start], alist[j] = alist[j], alist[start]
return j
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
i = int(input('The ith smallest element will be found. Enter i: '))
ith_smallest_item = select(alist, 0, len(alist), i)
print('Result: {}.'.format(ith_smallest_item))
# Program Explanation
# 1. The user is prompted to enter a list of numbers.
# 2. The user is then asked to enter i.
# 3. The ith largest element is found by calling select.
# 4. The result is displayed.
# Runtime Test Cases
# Case 1:
# Enter the list of numbers: 3 1 5 10 7 2 -2
# The ith smallest element will be found. Enter i: 2
# Result: 7.
# Case 2:
# Enter the list of numbers: 5 4 3 2 1
# The ith smallest element will be found. Enter i: 5
# Result: 1.
# Case 3:
# Enter the list of numbers: 3
# The ith smallest element will be found. Enter i: 1
# Result: 3. | true |
3f07333fe11b65981a4d530cc59ff45e42fe8225 | ssaroonsavath/python-workplace | /conversion/conversion.py | 977 | 4.25 | 4 | '''
Created on Jan 20, 2021
The objective is to make a program that can complete different conversions
'''
#Use input() to get the number of miles from the user. ANd store
#that int in a variable called miles.
miles = input("How many miles would you like to convert?")
#Convert miles to yards, using the following:
#1 mile = 1760
#Store the value in a variable called yards and print it our with a
#simple statement.
yards = miles * 1760
print(str(miles)) + "convert to" + str(yards) + "yards."
#conver miles to feet, using the following
# 1 mile = 5280 feet.
#Store the balue in a variable called feet and print it our with a
#simple statement
feet = miles * 5280
print(str(miles)) + "convert to" + str(feet) + "feet."
#conver miles to inches, using the following:
#1 mile = 63,360 feet
#Store the value in a variable called inches and print it our with a
#simple statement.
inches = miles * 63360
print(str(miles)) + "convert to" + str(inches) + "inches."
| true |
7686831590125c15617128a0115e1a23b084d528 | mayanderson/python-selenium-automation | /hw3_algorithms/algorithm_2.py | 298 | 4.15625 | 4 | def longestWord():
sentence = input('Please enter a sentence with words separated by spaces:')
words = sentence.split()
if len(words) == 0: return ""
if len(words) == 1: return words[0]
longest = ""
for word in words:
if len(word) > len (longest): longest = word
return longest | true |
658408212c2953a13931535581cbd34f9f446d83 | chokrihamza/opp-with-python | /try_except.py | 496 | 4.125 | 4 | try:
print(x)
except:
print("there is no value of x")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
try:
f = open("demofile.txt", 'w')
f.write("Hello there")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
| true |
7ddab1a480e5e4ab6d33ce0bec4039a590547973 | Rohankrishna/Python_Scripting_Practice | /even_odd.py | 383 | 4.15625 | 4 | from math import sqrt
n = int(input("enter a number "))
check = int(input("Enter the number with which we want to check "))
if n % 4 == 0:
print("It is an even number and also a multiple of 4")
elif n%2==0:
print("It is an even number")
else:
print("It is an odd number")
if(n%check==0):
print(n, " is evenly divisible by ",check)
else:
print(n, "is not divisible by", check)
| true |
980b7a7e9e0eb54fdb5e45109285da68ca5dafec | brownd0g/Financial-Independence-Calculator | /Financial Independence Calculator.py | 2,070 | 4.375 | 4 |
# This function is used to make sure user inputs a valid number for each question
def validInput(question):
UI = input(question)
# The following will run until a positive real number is entered
while True:
try:
num = float(UI)
while num < 0:
num = float(input("Error: Please enter a positive real number: "))
except ValueError:
UI = input("Error: Please enter a positive real number: ")
continue
else:
return num
break
# Use function to ask for input
expenses = validInput("How much did you spend last year to support your current lifestyle? ")
inf_rate = validInput("Please enter the expected inflation rate: ")
savings = validInput("How much do you currently have saved for investment? ")
interest = validInput("What is the expected average annual interest rate? ")
test_years = int(validInput("How many years do you want to test? "))
# Print the header
print("Year Remaining Balace")
# For loop to calculate each year
for x in range(0, test_years):
if savings > 0:
expenses = expenses + (expenses * inf_rate) # Adds inflation to expenses
savings = savings - expenses # Subtracts expenses from savings
savings = savings + (savings * interest) # Adds interest onto savings
if (x+1) < 10:
print("", x+1, " ", format(savings, '0.2f')) # Prints out current balance to two decimal places
else:
print("", x+1, " ", format(savings, '0.2f')) # Loses a space for formatting purposes
else:
print("Not financially independant!") # Waits for user input before exiting
input("Press enter to exit")
exit()
print("Financially independant!")
input("Press enter to exit")
exit()
| true |
2c7883d2c464936c5fb2bfc6d6e62ccab313b6ce | ggsbv/pyWork | /compareDNA/AminoAlign.py | 1,526 | 4.21875 | 4 | #findLargest function finds and returns the largest DNA string
def findLargest(AA1, AA2):
largest = ""
if len(AA1) >= len(AA2):
largest = AA1
else:
largest = AA2
return largest
#align function compares two amino acid sequences and prints any differences (mutations)
def align(AA1, AA2):
index = 0
match = 0.0
alignment = []
largestAA = findLargest(AA1, AA2)
print largestAA
while index < len(largestAA):
currentAA1 = AA1[index]
currentAA2 = AA2[index]
if currentAA1 != currentAA2:
alignment.append("_")
else:
alignment.append("*")
match += 1
index += 1
alignString = "".join(alignment)
percent = round((match/len(largestAA))*100, 2)
print "AA Sequence 1: " + AA1
print "AA Sequence 2: " + AA2
print '{:>15}'.format(alignString)
print "Alignment: " + str(percent)
AASeq1 = raw_input("Input first amino acid sequence to be compared. \nAlternatively you can type 'q' to quit. \n")
AASeq2 = raw_input("Input second amino acid sequence to be compared. \nAlternatively type 'q' to quit. \n")
while AASeq1 != "q" and AASeq2 != "q":
align(AASeq1, AASeq2)
AASeq1 = raw_input("Input first amino acid sequence to be compared. \nAlternatively you can type 'q' to quit. \n")
AASeq2 = raw_input("Input second amino acid sequence to be compared. \nAlternatively type 'q' to quit. \n")
| true |
e7c0faf8127f813db4bd4599198c8f6eda8ff552 | alexjohnlyman/Python-Exercises | /Inheritance.py | 1,003 | 4.21875 | 4 | # Inheritance
# Is an "is a" relationship
# Implicit Inheritance
class Parent(object):
def implicit(self):
print "PARENT implicit()"
def explicit(self):
print "PARENT explicit()"
def altered(self):
print "PARENT altered()"
class Child(Parent):
def implicit(self):
print "CHILD implicit()"
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered() # this will display "PARENT altered()". The 'super' takes 2 parameters super(class that you are trying to get the parent/super of, self)
print "CHILD, AFTER PARENT altered()"
# dad = Parent()
# son = Child()
# #
# # dad.implicit()
# # son.implicit()
# #
# # dad.explicit()
# # son.explicit()
#
# dad.altered()
# son.altered()
class Cat(object):
def speak(self):
print "meow"
class Lion(Cat):
def speak(self):
super(Lion, self).speak()
print "roar"
# felix = cat()
leo = Lion()
# felix.speak()
leo.speak()
| true |
298ab47829b2875bca88208e9d87d2d1ceb8a96f | LinuxLibrary/Python | /Py-4/py4sa-LA/programs/04-Classes.py | 864 | 4.28125 | 4 | #!/usr/bin/python
# Author : Arjun Shrinivas
# Date : 03.05.2017
# Purpose : Classes in Python
class Car():
def __init__(self):
print "Car started"
def color(self,color):
print "Your %s car is looking awesome" % color
def accel(self,speed):
print "Speeding upto %s mph" % speed
def turn(self,direction):
print "Turning " + direction
def stop(self):
print "Stop"
car1 = Car()
print car1
print car1.color('Black Chevrolet Cobalt SS')
print car1.accel(50)
print car1.turn('Right')
print car1.stop()
class RaceCar(Car):
def __init__(self,color):
self.color = color
self.top_speed = 200
print "%s race car has started with a top speed of %s" % (self.color, self.top_speed)
def accel(self, speed):
print "%s speeding up to %s mph very very fast" % (self.color, speed)
car2 = RaceCar('Black Chevrolet Cobalt SS')
print car2
print car2.accel(80)
# END
| true |
97b7f50d9511e5acd7a86947b8bc5a367f4b589d | brookstawil/LearningPython | /Notes/7-16-14 ex1 Problem Square root calculator.py | 935 | 4.3125 | 4 | #7/16/14
#Problem: See how many odd integers can be subtracted from a given number
#Believe it or not this actually gives the square root, the amount of integers need is the square root!!
#number input
num = int(input("Give me a number to square root! "))
num_begin = num
#Loops through the subtractions
#defines the start number we are subtracting num with
#It also defines the start of the count for how many integers are needed
subtracter = 1
ints_needed = 1
#Commenting out the print statements SIGNIFICANTLY increases speed
#Loop
while (num > subtracter):
print(str(ints_needed) + ": The odd integer used is " + str(subtracter))
num = num - subtracter
subtracter += 2
ints_needed += 1
#Prints the amount of integers needed
print(str(ints_needed),"odd integers were needed ending at " + str(subtracter) + " which would make the number negative")
print("The square root of",num_begin,"is",ints_needed)
| true |
2af694a25d9f9174581cd14f3eafad232b278f83 | brookstawil/LearningPython | /Notes/7-14-14 ex6 Letter grades.py | 525 | 4.125 | 4 | #7-14-14
#Letter grades
#Input the grade
grade = input("What is the grade? ")
grade = grade.upper()
#Long way
#if grade == "A":
# print ("A - Excellent")
#else:
# if grade == "B":
# print("B - good!")
# else:
# if grade == "C":
# print("C - average")
# else:
# print =(grade,"other")
#Short way
#elif combines the else and if statement
if grade == "A":
print("A - Excellent!")
elif grade == "B":
print("B - Good!")
elif grade == "C":
print("C - average")
| true |
ec1f9eb074b9429219c410c902a440cea069377e | brookstawil/LearningPython | /Notes/7-31-14 ex1 Determine whether a number (N) is prime.py | 958 | 4.1875 | 4 | #7/31/14
#Determine whether a number (N) is prime or not
#We only have to check numbers up to the integer square root of N.
import math
#This determines whether n is prime
#INPUT - a number to check
#OUTPUT - Ture if it is prime or False if is is not
def is_prime(n):
is_it_prime = True #We start with an assumption that it is prime
divisor = 2 #This is the first divisor
while (divisor <= math.sqrt(n)): #We use a while loop because we don't know how many iterations are needed
#Is it divisible?
if (n % divisor == 0): #Its divisible
is_it_prime = False
break #Stops checking
divisor += 1#Try the next divisor
return is_it_prime
def main():
how_many_primes = 1000
counter_primes = 0
n = 2
while(counter_primes < how_many_primes):
if is_prime(n) == True:
counter_primes += 1
print("%8d" % n,end = "")
n += 1
main()
| true |
d85e661fcc6f61c320b8502dde6c185d5a50f78a | Struth-Rourke/cs-module-project-algorithms | /moving_zeroes/moving_zeroes.py | 787 | 4.34375 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
def moving_zeroes(arr):
# instantiating an empty, new_arr
new_arr = []
# loop over items in the array
for i in arr:
# if the value of the item in the array is not zero
if i != 0:
# append the value to the list
new_arr.append(i)
# loop over the items again, seperately (second occasion)
for j in arr:
# if the value of the item in the array IS zero
if j == 0:
# append it to the list
new_arr.append(j)
return new_arr
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
| true |
3a9aaa5e252c042a99972e7a7146e17a9ddae7e4 | parandkar/Python_Practice | /brick_game.py | 933 | 4.15625 | 4 | """
This is a solution to the problem given at
https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/bricks-game-5140869d/
Patlu and Motu works in a building construction, they have to put some number of bricks N from one place to another, and started doing their work. They decided , they end up with a fun challenge who will put the last brick.
They to follow a simple rule, In the i'th round, Patlu puts i bricks whereas Motu puts ix2 bricks.
There are only N bricks, you need to help find the challenge result to find who put the last brick.
Input:
First line contains an integer N.
Output:
Output "Patlu" (without the quotes) if Patlu puts the last bricks ,"Motu"(without the quotes) otherwise.
"""
N = int(input())
round = 1
while N > (round * 3):
N -= (round * 3)
round += 1
if N/round > 1.000:
print("Motu")
else:
print("Patlu")
| true |
efccbfe53442920f68dba5e07a6de8f05ded48a4 | parandkar/Python_Practice | /seat.py | 733 | 4.1875 | 4 | """
This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/seating-arrangement-1/
"""
# Using dictionaries to deduce the front seats and seat type
facing_seats = {1:11, 2:9, 3:7, 4:5, 5:3, 6:1, 7:-1, 8:-3, 9:-5, 10:-7, 11:-9, 0:-11}
seat_types = {1:'WS', 0:'WS', 2:'MS', 5:'MS', 3:'AS', 4:'AS'}
# Get the number of inputs
T = int(input())
# Getting the N inputs and strring them in an array
N_Array = []
# get the facing seat numbers and seat types
for n in range(0, T):
N_Array.append(int(input()))
for seat in N_Array:
print(seat + facing_seats[seat%12], end=' ')
print(seat_types[seat%6])
| true |
625c2fb420c9fb2670a4bf01db08aaa52ccc5080 | parandkar/Python_Practice | /count-divisors.py | 694 | 4.1875 | 4 | """
This is a solution to the problem given at https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/count-divisors/
You have been given 3 integers - l, r and k. Find how many numbers between l and r (both inclusive) are divisible by k. You do not need to print these numbers, you just have to find their count.
Input Format
The first and only line of input contains 3 space separated integers l, r and k.
Output Format
Print the required answer on a single line.
"""
I, r, k = map(int, input().split())
num_of_divisors = 0
for i in range(I, r+1):
if i%k == 0:
num_of_divisors += 1
print(num_of_divisors)
| true |
a4cfcbfcad47b05b4257e2251ba015f2226761ae | chuene-99/Python_projects | /mostwords.py | 410 | 4.25 | 4 | #program that counts the most common words in a text file.
file=open(input('enter file name: '))
list_words=list()
dict_words=dict()
for line in file:
line=line.rstrip()
line=line.split()
for word in line:
dict_words[word]=dict_words.get(word,0)+1
for k,v in dict_words.items():
list_words.append((v,k))
list_words.sort(reverse=True)
for v,k in list_words:
print(k,v)
| true |
744f607a516a3d874bd33b80c8b599a75e18e2a2 | rednikon/Python | /String-Functions/mymodB.py | 937 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 9 17:21:10 2019
@author: veemac
"""
COMMA = ','
SPACE = ' '
BLANK = ''
PERIOD = '.'
name = "Alexandria Ocasio-Cortez"
def initials(name):
"""Given a name returns the initials.
>>> initials('Elon Reeve Musk')
'E.R.M.'
>>> initials('Lyndon Baines Johnson')
'L.B.J.'
>>> initials('Franklin Delano Roosevelt')
'F.D.R.'
>>> initials('Alexandria Ocasio-Cortez')
'A.O.C.'
"""
# REPLACE THE pass BELOW WITH YOUR OWN CODE
return (PERIOD.join(name[0].upper() for name in name if name.isupper()) + PERIOD)
def name2tuple(name):
"""Given a comma-separated name, returns a tuple of the form (firstnames, lastnames).
>>> tvhost = "Maddow, Rachel Anne"
>>> name2tuple(tvhost)
('Rachel Anne', 'Maddow')
>>> author = "Borges Acevedo, Jorge Francisco Isidoro Luis"
>>> name2tuple(author)
('Jorge Francisco Isidoro Luis', 'Borges Acevedo')
"""
# REPLACE THE pass BELOW WITH YOUR OWN CODE
return (COMMA.join(name.split(SPACE)[::-1])) | false |
a2c58ea778e8581d580dff71681023bb0b2f53e0 | porkpiie/pythonweek | /asciicheck.py | 319 | 4.125 | 4 | alpha=input("Enter any letter: ")
if ord(alpha)>=65 and ord(alpha)<=90:
print("Capital letter")
else:
if ord(alpha)>=97 and ord(alpha)<=122:
print("Lower case")
else:
if ord(alpha)>=48 and ord(alpha)<=57:
print("Digits")
else:
print("Any other character") | false |
a6c81c911cda7b995456e893b71b400713a8c34d | ry-blank/Module-7 | /basic_list.py | 878 | 4.53125 | 5 | """
Program: basic_list_assignment
Author: Ryan Blankenship
Last Date Modified: 10/6/2019
The purpose of this program is to take user
input then display it in a list.
"""
def make_list():
"""
function to return list of user input from function get_input()
:return: returns list of user input
"""
number_list = []
attempts = 3
for a in range(attempts):
try:
user_num = int(get_input())
except ValueError:
print("Please enter numbers only.")
else:
number_list.insert(len(number_list), user_num)
return number_list
def get_input():
"""
function to prompt user for input
:return: returns a string
"""
user_num = input("Please enter a number to add to your list: ")
return user_num
if __name__ == '__main__':
print(make_list())
| true |
8d022903c89a5f24d5b99aba8e273ecdce4c2bb2 | Hail91/Algorithms | /recipe_batches/recipe_batches.py | 1,683 | 4.125 | 4 | #!/usr/bin/python
import math
test_recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } # Test for PT
test_ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } # Test for PT
def recipe_batches(recipe, ingredients):
batches = 0 # Initalize a batches variable to zero
while True: # Using a while loop to keep the loop running <--- Should probably refactor this as while True is not very clear.
for value in recipe: # Loop over recipe dictionary grabbing values out.
if value not in ingredients: # If there is a value in recipes that is not in ingredients, break out of the loop and return batches.
return batches
elif recipe[value] > ingredients[value]: # Otherwise, if the value exists in both dictionaries, but there is not enough in the ingredients dict, then break and return batches.
return batches
else: # Otherwise, that means you have enough of that "Value(ingredient)", so subtract the amount required in recipes from the ingredients dict for that specifc ingredient.
ingredients[value] -= recipe[value]
batches += 1 # Increment batches by 1 once you've completed one full loop through the recipes dict where all conditions are passing.
recipe_batches(test_recipe, test_ingredients) # Test for PT
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients)) | true |
e1fbb0394458201d27b22d8df48b5df97b5e31c1 | ShabnamSaidova/basics | /dogs.py | 2,438 | 4.46875 | 4 | class Dog():
"""A simple attempt to model a dog"""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting. ")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(self.name.title() + " rolled over!")
mydog = Dog('Bob', 6)
yourdog = Dog('willie', 5)
mydog.sit()
mydog.roll_over()
print("Your dog's name is " + yourdog.name.title() + ".")
print("Your dog is " + str(yourdog.age) + " years old. ")
print("My dog is " + str(mydog.age) + " years old. ")
yourdog.sit()
print("\nExercise 9-1")
# 9-1. Restaurant: Make a class called Restaurant. The __init__() method for
# Restaurant should store two attributes: a restaurant_name and a cuisine_type.
# Make a method called describe_restaurant() that prints these two pieces of
# information, and a method called open_restaurant() that prints a message indi-
# cating that the restaurant is open.
# Make an instance called restaurant from your class. Print the two attri-
# butes individually, and then call both methods.
class Restaurant():
"""Restaurant should store two attributes: a restaurant_name and a cuisine_type."""
def __init__(self, name, cuisine):
self.name = name.title()
self.cuisine = cuisine.title()
def describe_restaurant(self):
message = f"{self.name} serves wonderful {self.cuisine} ."
print(f"\n{message}")
def open_restaurant(self):
message = f"{self.name} is now open!"
print(f"\n{message}")
restaurant = Restaurant('Luigi', 'pizza')
print(restaurant.name)
print(restaurant.cuisine)
restaurant.describe_restaurant()
restaurant.open_restaurant()
class Car():
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
my_new_car = Car('audi', 'q5', 2014)
print(my_new_car.get_descriptive_name()) | true |
cb5b3c72a8482ce9be3b8b4991527eeada7c27fd | Marcus-Mosley/ICS3U-Unit4-03-Python | /squares.py | 1,024 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by Marcus A. Mosley
# Created on October 2020
# This program finds the squares of all natural numbers preceding the
# number inputted by the user
def main():
# This function finds the squares of all natural numbers preceding the
# number inputted by the user
# Input
counter = 0
square = 0
natural_string = input("Enter a natural number (To Find Sqaure 0 to N): ")
print("")
# Process & Output
try:
natural_integer = int(natural_string)
except Exception:
print("You have not inputted an integer, please input an integer"
" (natural number)!")
else:
if natural_integer <= 0:
print("You have not inputted a positive number, please input a"
" positive number!")
else:
for counter in range(natural_integer+1):
square = counter**2
print("The square of {0} is {1}".format(counter, square))
if __name__ == "__main__":
main()
| true |
b18eda77ffe0121752bb93beb291eab3184f0df2 | Udayin/Flood-warning-system | /floodsystem/flood.py | 1,586 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 24 18:01:03 2017
@author: Rose Humphry
"""
from floodsystem.utils import sorted_by_key
def stations_level_over_threshold(stations, tol):
''' a function that returns a list of tuples,
where each tuple holds (1) a station at which the latest
relative water level is over tol and (2) the relative water
level at the station. The returned list should be sorted
by the relative level in descending order.'''
stations_over_threshold = []
for station in stations:
if type(station.relative_water_level()) == float:
if station.relative_water_level() > tol:
station_tup = (station.name, station.relative_water_level())
stations_over_threshold.append(station_tup)
stations_over_threshold.sort()
return stations_over_threshold
def stations_highest_rel_level(stations, N):
'''A function that takes a list of stations and
returns a list of the N stations at which the water level,
relative to the typical range, is highest. The list should
be sorted in descending order by relative level.'''
most_at_risk_stations = []
for station in stations:
if type(station.relative_water_level()) == float:
x = station.relative_water_level()
most_at_risk_stations += [(station, float("{0:.6f}".format(x)))]
else:
pass
sorted_most_at_risk_stations = sorted_by_key(most_at_risk_stations, 1, True)
return sorted_most_at_risk_stations[:N]
| true |
fd5982d54adcca536876f48003c814f73ea227f6 | G3Code-CS/Algorithms | /making_change/making_change.py | 2,643 | 4.375 | 4 | #!/usr/bin/python
import sys
def making_change(amount, denominations):
# we can initialize a cache as a list (a dictionary
# would work fine as well) of 0s with a length equal to the amount we're
# looking to make change for.
cache = [0] * (amount + 1)
# Since we know there is one way to
# make 0 cents in change, we'll initialize `cache[0] = 1`
cache[0] = 1
# Now that we've initialized our cache, we'll start building it up. We have an
# initial value in our cache, so we'll want to build up subsequent answers in
# terms of this initial value. So, for a given coin, we can loop through all of
# the higher amounts between our coin and the amount (i.e., `for higher_amount
# in range(coin, amount + 1)`). If we take the difference between the higher
# amount and the value of our coin, we can start building up the values in our
# cache.
# To go into a little more detail, let's walk through a small example. If we
# imagine our coin is a penny, in the first loop iteration, `higher_amount` is
# going to be 1 (since it will at first be the same value as our coin). If we
# take the difference between `higher_amount` and our coin value, we get 0. We
# already have a value for 0 in our cache; it's 1. So now we've just figured
# out 1 way to 1 cent from a penny. Add that answer to our cache.
# Next up, on the next iteration, `higher_amount` will now be 2. The difference
# between `higher_amount` and our coin value now is 1. Well we just figured out
# an answer for 1, so now we have an answer for 2. Add that to our cache.
# Once this loop finishes, we'll have figured out all of the ways to make
# different amounts using the current coin. At that point, all we have to do is
# perform that loop for every single coin, and then return the answer in our
# cache for the original amount!
for coin in denominations:
for higher_amount in range(coin, amount+1):
coin_value = higher_amount - coin
cache[higher_amount] += cache[coin_value]
return cache[amount]
# print(making_change(10, [1, 5, 10, 25, 50]))
if __name__ == "__main__":
# Test our your implementation from the command line
# with `python making_change.py [amount]` with different amounts
if len(sys.argv) > 1:
denominations = [1, 5, 10, 25, 50]
amount = int(sys.argv[1])
print("There are {ways} ways to make {amount} cents.".format(ways=making_change(amount, denominations), amount=amount))
else:
print("Usage: making_change.py [amount]")
| true |
de000242afafc8fa391cce60c3ad3a0f3c356c15 | balapitchuka/python-utilities | /operator-override.py | 571 | 4.46875 | 4 | # example of overriding operators
# operator overriding
class Value:
def __init__(self, value):
self.value = value
# - __sub__, * __mul__, ** __pow__, / __truediv__, // __floordiv__, % __mod__
# << __lshift__, >> __rshift__, & __and__, | __or__, ^ __xor__, ~ __invert__
# < __lt__, <= __le__, == __eq__, != __ne__, > __gt__, >= __ge__
def __add__(self, other):
return Value(" -[ "+self.value +" ]- -[ "+ other.value+" ]- ")
def __str__(self):
return self.value
v1 = Value("line#1")
v2 = Value("line#2")
print(v1 + v2)
| false |
dc80c11937f7c56683556b60f211fd3504539c60 | Avulaparvathi/pythontraining | /rock paper sc game.py | 1,246 | 4.15625 | 4 | p1=input("enter the choice")
p2=input("enter the choice")
while True:
if p1==p2:
print("tie")
elif p1=="rock":
if p2=="scissors":
print("congratulatipns to p1")
else:
print("congratulation to p2")
elif p1=="paper":
if p2=="rock":
print("congratulations to p1")
else:
print("congratulations to p2")
elif p1=="scissors":
if p2=="rock":
print("congratulations to p2")
else:
print("congratulations to p1")
playagain=input("play again? yes or no")
if playagain!="yes":
break
def rpsgame(p1,p2):
while True:
if p1 == p2:
print("tie")
elif p1 == "rock":
if p2 == "scissors":
print("congratulatipns to p1")
else:
print("congratulation to p2")
elif p1 == "paper":
if p2 == "rock":
print("congratulations to p1")
else:
print("congratulations to p2")
elif p1 == "scissors":
if p2 == "rock":
print("congratulations to p2")
else:
print("congratulations to p1")
playagain = input("play again? yes or no")
if playagain != "yes":
break
return 0
rpsgame("rock","paper") | false |
8bbdb6e9157642e89e718d51a76f674d5fa177be | ethirajmanoj/Python-14-6-exercise | /14-quiz.py | 1,062 | 4.1875 | 4 | # Create a question class
# Read the file `data/quiz.csv` to create a list of questions
# Randomly choose 10 question
# For each question display it in the following format followed by a prompt for answer
"""
<Question text>
1. Option 1
2. Option 2
3. Option 3
4. Option 4
Answer ::
"""
import csv
score = 0
score = int(score)
f = open("quiz.csv",'r')
d=csv.reader(f)
next(f) #To Skip Header Row
k = 0
adm = str(input(""))
for row in d:
if str(row[0])==adm:
print("Que:= ", row[1])
print("01 = ", row[2])
print("02 = ", row[3])
print("03 = ", row[4])
print("04 = ", row[5])
#print("Key = ", row[6])
answer = input("Key: ")
if answer ==str(row[6]):
print("Correct!")
score = score + 1
else:
print("Incorrect, Correct Answer is " + str(row[6]))
print("Your current score is " + str(score) + " out of 10")
# Keep score for all right and wrong answer
# Take an extra step and output the correct answer for all wrong answers at the end
| true |
b9c7eee17e69a1836d0cbf817509a874ebe5514f | nsvir/todo | /src/model/list_todo.py | 1,158 | 4.125 | 4 | class ListTodo:
"""
List Todo contains name
Initialize an empty list
lst = ListTodo()
To get list
>>> lst.list()
[]
To add element in list
lst.add_list(TaskList())
To check if element is contained in list
lst.contains_list(TaskList())
True
"""
def __init__(self):
self.__lst = []
def list(self) :
return self.__lst
def contains_list(self, tasklist):
for listt in self.__lst:
if listt.name() == tasklist.name():
return True
return False
def contains_list_by_name(self, listname):
for listt in self.__lst:
if listt.name() == listname:
return True
return False
def add_list(self, taskList):
self.__lst.append(taskList)
def get_list(self, namelist):
for listt in self.__lst:
if listt.name() == namelist:
return listt
return None
def remove_list(self, namelist):
newlst = []
for lst in self.__lst:
if lst.name() != namelist:
newlst.append(lst)
self.__lst = newlst | true |
acee050f0b233e3769df049dc44bd5cfb6af31e3 | UJurkevica/python-course | /homework/week2/exercise1.py | 538 | 4.21875 | 4 | #1a
for num in range(0,11):
if num % 3 == 0:
continue
else:
print(f'number {num}')
#1b
def print_nums():
for num in range(0,10):
if num % 3 == 0:
continue
else:
print(f'Number in function range {num}')
print_nums()
#1c
max_number = int(input('Enter positive maximum print range value '))
def print_nums():
for num in range(max_number):
if num % 3 == 0:
continue
else:
print(f'Number in function range {num}')
print_nums() | false |
f52d7a33408b9645e8b66ddd580e9192732b3021 | vitaliy-developer/learning_python | /5.operator.py | 762 | 4.15625 | 4 | number = int(input("Enter a number: "))
if number > 5:
print("This number > 5")
else:
print("Number < 5")
name = input("Enter you name: ")
if name == "Alex":
print("You have entered", name)
print("This is my name, too.")
else:
print("You not Alex")
x = int(input(" x = "))
if 0 < x < 7:
print("значение")
y = 2 * x - 5
if y < 0:
print("negative")
elif y > 0:
print("positive")
else:
print("y = 0")
print("""
1. file
2. View
3. Exit
""")
choise = input("Enter you choise: ")
if choise == "1":
print("You have selected 'File' menu")
elif choise == "2":
print("You have selected 'View' menu")
elif choise == "3":
print("Stoping.")
else:
print("Incorected choise") | false |
d306f43d54d0a2713bc23a714a949af59714e9f4 | Yosolita1978/Google-Basic-Python-Exercises | /basic/wordcount.py | 2,898 | 4.34375 | 4 |
"""Wordcount exercise
Google's Python class
1. For the --count flag, implement a print_words(filename) function that counts
how often each word appears in the text and prints:
word1 count1
word2 count2
...
Print the above list in order sorted by word (python will sort punctuation to
come before letters -- that's fine). Store all the words as lowercase,
so 'The' and 'the' count as the same word.
2. For the --topcount flag, implement a print_top(filename) which is similar
to print_words() but which prints just the top 20 most common words sorted
so the most common word is first, then the next most common, and so on.
Use str.split() (no arguments) to split on all whitespace.
Workflow: don't build the whole program at once. Get it to an intermediate
milestone and print your data structure and sys.exit(0).
When that's working, try for the next milestone.
Optional: define a helper function to avoid code duplication inside
print_words() and print_top().
"""
def process_file(filename):
with open(filename, "rU") as my_file:
my_file_list = my_file.readlines()
return my_file_list
def count_words(file_list):
words_count = {}
for phrase in file_list:
lower_phrase = phrase.lower().split()
for word in lower_phrase:
if word not in words_count:
words_count[word] = 1
else:
words_count[word] +=1
return words_count
def print_sorted(dic):
for key in sorted(dic.keys()):
print key , ":" , dic[key]
def top_count(dic):
def count(key):
return dic[key]
top = sorted(dic, key=count, reverse= True)
for key in top[:20]:
print key, dic[key]
def menu_gral():
menu = ("""
Hello There!
What file do you want to process:
1. Small
2. Alice
3. Exit
""")
option = raw_input(menu)
return option
def menu_file():
menu = ("""
What do you want to do with this file:
1. Count words:
2. Count top words
3. Return gral menu
""")
option = raw_input(menu)
return option
def main():
user_choice = menu_gral()
while True:
if user_choice == "1":
my_file_small = process_file("/Users/cristina/source/google-python-exercises/basic/small.txt")
dictionary_small = count_words(my_file_small)
question = menu_file()
if question == "1":
print_sorted(dictionary_small)
elif question == "2":
top_count(dictionary_small)
else:
user_choice = menu_gral()
elif user_choice == "2":
my_file_alice = process_file("/Users/cristina/source/google-python-exercises/basic/alice.txt")
dictionary_alice = count_words(my_file_alice)
question = menu_file()
if question == "1":
print_sorted(dictionary_alice)
elif question == "2":
top_count(dictionary_alice)
else:
user_choice = menu_gral()
else:
break
if __name__ == '__main__':
main()
| true |
9368e573f0bd816c214165e71571bccfed73076d | ThomasP1234/DofE | /Week 2/GlobalVariables.py | 527 | 4.125 | 4 | # Global Variables and Scope
# ref: https://www.w3schools.com/python/
# Author: Thomas Preston
x = "awesome" # When this is commented out there is an error because the final print doesn't know what x is
def myfunc():
x = "fantastic" # Where as when this is commented out, the global x is printed
print("Python is " + x)
myfunc()
print("Python is " + x)
# You can add a variable to the global scope using the global keyword
def func():
global y
y = "super"
print("Python is " + y)
func()
print ("Python is " + y) | true |
95f146d5bd21e8f40343ea95c4f7e8f7ea0da0f8 | ThomasP1234/DofE | /Week 5/WhileLoops.py | 410 | 4.21875 | 4 | # One of the primary loops in python
# ref: https://www.w3schools.com/python/
# Author: Thomas Preston
a = 1
while a < 10:
print(a)
a = a + 1 # Adds 1 to a each loop
b = 1
while b < 6:
print(b)
if b == 3:
break
b += 1
c = 0
while c < 6:
c += 1
if c == 3:
continue
print(c) # skips this step when c = 3
d = 1
while d < 10:
print(d)
d = d + 1
else:
print('d is not long < 10') | true |
5caa1ea1ab9aab2e1a85af0092d644ce36d8e8b1 | Mrityunjay6492/python | /day program.py | 1,929 | 4.375 | 4 | # To determine the day at that the Entered date
def date(dd,mm,yyyy):
m=[31,28,31,30,31,30,31,31,30,31,30,31] #assinment, number of days in month's
if(yyyy%4==0): #increment of 1 for a leap year in the month of feb
m[1]=29
days=0
for i in range(0,mm-1,1): #calculating the number of days in till mm months
days+=m[i]
if yyyy>=2000: #as the reference is year 2000, if year entered by user is grearter or equal to year 2000
days=days+dd-1
elif yyyy%4==0 and yyyy<2000: #year less then 2000 and is leap year
days=366-(days+dd)
elif yyyy%4!=0 and yyyy<2000: #year less then 2000
days=365-(days+dd)
year=yyyy-2000 #difference between year 2000 and the year provided to function
if year>=0:
leap=year//4 #leap year between the years
else:
leap=year//4+1 #The negetive integer tends to shift left side, so to counter that one is added to the division
if year%4!=0 and yyyy>2000: # counter the no. of leap year between non
leap+=1
year=abs(year+leap)+days
daynum=year%7
if(yyyy<2000 and daynum!=0):
k=5
for i in range(1,daynum,1):
k-=2
daynum+=k
if daynum==0:
print("the day is saturday")
elif daynum==1:
print("the day is sunday")
elif daynum==2:
print("the day is monday")
elif daynum==3:
print("the day is tuesday")
elif daynum==4:
print("the day is wednesday")
elif daynum==5:
print("the day is thursday")
elif daynum==6:
print("the day is friday")
else:
print("does not exist")
| false |
9fba4c0eb7046f9b22e1f3a83e0752c961fedcd4 | Yfaye/AlgorithmPractice | /python/InsertInterval.py | 1,756 | 4.25 | 4 | # Insert Interval
# Description
# Given a non-overlapping interval list which is sorted by start point.
# Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).
# Example
# Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].
# Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].
# Tags
# Basic Implementation LinkedIn Google
# Related Problems
# Easy Merge Intervals 20 %
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
intervals.append(newInterval)
sortedIntervals = sorted(intervals, key = lambda x: (x.start, x.end))
i = 0
while i < len(sortedIntervals) - 1: # 总是忘记这里的range是 i < length - 1, 因为下面都要检查到i+1
if (sortedIntervals[i].end >= sortedIntervals[i+1].end):
del sortedIntervals[i+1]
elif (sortedIntervals[i].end < sortedIntervals[i+1].end and sortedIntervals[i].end >= sortedIntervals[i+1].start):
sortedIntervals[i].end = sortedIntervals[i+1].end
del sortedIntervals[i+1]
else:
i += 1
return sortedIntervals
# 这题跟merge Intervals 是完全一样的一道题,就是多一个append操作。但是如果一开始出的是这一道题,就比merge 更难想到一些......
# 这两题自己都用的是排序好后删除的做法,下次要试一下用一个空数组然后生成的方法 | true |
4147e66c5a23d70dfe1d885f5816949e808b52d5 | GitFromAleksey/pyLearn | /OOP/simpleclass.py | 1,011 | 4.34375 | 4 |
##------------------------------------------------------------------------------
class SimpleClass: # имя класса
u'Simple Class __doc__'
var = 87 # совместно используемая переменная
'Simple Class constructor'
def __init__(self):
## self.var = 99
print('SimpleClass.Constructor ')
print('self',self)
def display(self):
print ('display:', self.var, SimpleClass.var )
def f():
print ('Hello World')
def main():
smc = SimpleClass()
print(smc.__doc__)
print('SimpleClass.var = ', smc.var)
print('SimpleClass.f() = ', SimpleClass.f())
SimpleClass.var = 0
print('smc.var = ', smc.var)
smc.var = 1
print('SimpleClass.var = ', SimpleClass.var)
print('smc.var = ', smc.var)
SimpleClass.var = 2
print('SimpleClass.var = ', SimpleClass.var)
print('smc.var = ', smc.var)
## SimpleClass.display()
smc.display()
if __name__ == '__main__':
main()
| false |
bb711f3653e9dd1ae3f3a88d75a2fd038df612dc | vanctate/Computer-Science-Coursework | /CSCI-3800-Advanced-Programming/HW03/Problem1_Python/piece.py | 1,365 | 4.1875 | 4 | # Patrick Tate
# CSCI 3800 HW03 | Problem 1
# class to represent a black or white piece to be inserted into an Othello gameboard
# piece has a color(B/w), and a row and column in array notation, to be used with the Grid class
class Piece:
# subtract 1 from row and column for array notation
def __init__(self, color, row, column):
self.__color = color # char value 'B' or 'W'
self.__row = row - 1
self.__column = column - 1
def setRow(self, row):
self.__row = row
def setColumn(self, column):
self.__column = column
def getRow(self):
return self.__row
def getColumn(self):
return self.__column
def getColor(self):
return self.__color
# used in the Grid class when a valid move flips the colors of the trapped pieces
def getOppositeColor(self):
if self.__color == 'B':
return 'W'
elif self.__color == 'W':
return 'B'
else:
print("*** Error: Invalid color values ***")
return 'E'
# used in the Grid class when a valid move flips the colors of the trapped pieces
def flipColor(self):
if self.__color == 'B':
self.__color = 'W'
elif self.__color == 'W':
self.__color = 'B'
else:
print("*** Error: Invalid color values ***")
| true |
796695d867757555edc2d8fb69c3ece721544809 | test-python-rookie/python_study | /No11_集合.py | 751 | 4.125 | 4 | # 集合(set)是一个无序的不重复元素序列。
# 可以使用大括号 {} 或者 set() 函数创建集合,注意:创建一个空集合必须用set()而不是{},因为{}是用来创建一个空字典。
# 集合会自动去重且无序
parame1 = {"apple", "blue", "people", "people"}
print(parame1)
parame2 = set("好好学习,天天向上!!!")
print(parame2)
# 将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。
parame1.add("look")
print(parame1)
# 还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:
parame1.update(["a", "b"])
parame1.update([1, 2], [3,"gun"])
parame2.update({"name":"xiao"})
print(parame1)
print(parame2)
| false |
89a568f79f10a3bf0370d01f195813475979832a | akeeton/leetcode-python | /0283-move-zeroes.py | 1,676 | 4.1875 | 4 | """
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the
non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
class Solution:
@staticmethod
def bubble_sort_zeroes(nums):
is_sorted = False
while not is_sorted:
is_sorted = True
for left in range(len(nums) - 1):
right = left + 1
if nums[left] == 0 and nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
is_sorted = False
@staticmethod
def insertion_sort_zeroes(nums):
index_first_sorted_zero = None
for index_unsorted in range(len(nums)):
if nums[index_unsorted] == 0:
if index_first_sorted_zero is None:
index_first_sorted_zero = index_unsorted
continue
if index_unsorted == 0 or index_first_sorted_zero is None:
continue
nums[index_first_sorted_zero] = nums[index_unsorted]
nums[index_unsorted] = 0
index_first_sorted_zero += 1
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# Solution.bubble_sort_zeroes(nums)
Solution.insertion_sort_zeroes(nums)
def main():
sol = Solution()
nums_a = [0, 1, 0, 3, 12]
sol.moveZeroes(nums_a)
print(nums_a)
if __name__ == '__main__':
main()
| true |
5a7355772688b12e1897a208b6f3677ac36260e2 | Anz131/luminarpython | /Functions/functional programming/map.py | 397 | 4.21875 | 4 | # map to cover evey data in a list
# arr=[2,3,4,5,6]
#
# #find squares
#
# def square(num):
# return num**2
# #map(function?,iterable)
#
# squarelist=list(map(square,arr))
# print(squarelist)
# arr=[2,3,4,5,6]
#
# squarelist=list(map(lambda num:num**2,arr))
# print(squarelist)
# lst=["anu","appu","achu","kunju"]
#
# uppername=list(map(lambda name:name.upper(),lst))
# print(uppername)
| false |
2319f0735e3516b43da4890f2682fc9d9055868f | harekrushnas/python_practice | /guess_the_number.py | 1,513 | 4.21875 | 4 | #The program will first randomly generate a number unknown to the user. The user needs to guess what that number is.
# Reference link : https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/
import random
#from colorama import*
ran = random.randint(0,1000)
#len1=len(str(abs(ran)))
#print(ran,len1)
below_ran=random.randint(ran-5,ran)
above_ran=random.randint(ran,ran+5)
#print(ran)
print('Guess the number is in range of : ',below_ran,' and ',above_ran)
print('Provied your number below line and you have 3 chances in your hand ')
print('--------------------------------------------------------------------')
for i in range(3):
user_number = input(('PLEASE ENTER YOUR NUMBER :'))
#print (i)
if ran == int(user_number):
print('Congrats....your guess is correct....NUMBER=', ran)
break
else:
if i == 2:
print('Ohh...U missed all the chances....','\n You Lose the game',
'\n thanks for playing the game... ')
chk_no=input('Do you want to see the Actual Number ? Y/N :')
if chk_no=='Y' or chk_no=='y':
print ('The actual no is : ',ran)
else:
print('Thank u...')
else:
#print('Ohhh....Your guess is incorrect.......don\'t worry you have ',Fore.RED + 2-i +Style.RESET_ALL , 'chance left')
print('Ohhh....Your guess is incorrect.......don\'t worry you have ', 2 - i ,'chance left')
| true |
de3da113c7e0bbc9f73c2f2182539b2b0bb266c6 | frankPairs/head-first-python-exercises | /chapter_4_functions_modules/vsearch_set.py | 235 | 4.1875 | 4 | def search_for_vowels(word: str) -> set:
"""Returns any vowels found in a supplied word"""
vowels = set('aeiou')
return vowels.intersection(set(word))
print(search_for_vowels("francisco"))
print(search_for_vowels("sky"))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.