blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
31096b265c03c796fbac2e9adb05edf6cf74df49 | Frankiee/leetcode | /archived/array/1138_alphabet_board_path.py | 2,860 | 4.1875 | 4 | # [Archived]
# https://leetcode.com/problems/alphabet-board-path/
# 1138. Alphabet Board Path
# On an alphabet board, we start at position (0, 0), corresponding to
# character board[0][0].
#
# Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown
# in the diagram below.
#
#
# We may make the following moves:
#
# 'U' moves our position up one row, if the position exists on the board;
# 'D' moves our position down one row, if the position exists on the board;
# 'L' moves our position left one column, if the position exists on the board;
# 'R' moves our position right one column, if the position exists on the board;
# '!' adds the character board[r][c] at our current position (r, c) to the
# answer.
# (Here, the only positions that exist on the board are positions with
# letters on them.)
#
# Return a sequence of moves that makes our answer equal to target in the
# minimum number of moves. You may return any path that does so.
#
#
#
# Example 1:
#
# Input: target = "leet"
# Output: "DDR!UURRR!!DDD!"
# Example 2:
#
# Input: target = "code"
# Output: "RR!DDRR!UUL!R!"
#
#
# Constraints:
#
# 1 <= target.length <= 100
# target consists only of English lowercase letters.
class Solution(object):
board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
position = dict([
(board[r][c], (r, c))
for r in range(len(board))
for c in range(len(board[r]))
])
def punch_next(self, current_r, current_c, char, ret):
to_r, to_c = self.position[char]
while current_r != to_r or current_c != to_c:
while (to_r > current_r and
0 <= current_r + 1 < len(self.board) and
0 <= current_c < len(self.board[current_r + 1])):
ret += 'D'
current_r += 1
while (to_r < current_r and
0 <= current_r - 1 < len(self.board) and
0 <= current_c < len(self.board[current_r - 1])):
ret += 'U'
current_r -= 1
while (to_c > current_c and
0 <= current_r < len(self.board) and
0 <= current_c + 1 < len(self.board[current_r])):
ret += 'R'
current_c += 1
while (to_c < current_c and
0 <= current_r < len(self.board) and
0 <= current_c - 1 < len(self.board[current_r])):
ret += 'L'
current_c -= 1
ret += '!'
return to_r, to_c, ret
def alphabetBoardPath(self, target):
"""
:type target: str
:rtype: str
"""
ret = ""
current_r = current_c = 0
for c in target:
current_r, current_c, ret = self.punch_next(
current_r, current_c, c, ret,
)
return ret
| true |
681a2024de2d9d5091578a2299eae897946f02c7 | Frankiee/leetcode | /archived/string/383_ransom_note.py | 1,189 | 4.125 | 4 | # [Archived]
# https://leetcode.com/problems/ransom-note/
# 383. Ransom Note
# Given an arbitrary ransom note string and another string containing
# letters from all the magazines, write a function that will return true if
# the ransom note can be constructed from the magazines ; otherwise, it will
# return false.
#
# Each letter in the magazine string can only be used once in your ransom note.
#
# Note:
# You may assume that both strings contain only lowercase letters.
#
# canConstruct("a", "b") -> false
# canConstruct("aa", "ab") -> false
# canConstruct("aa", "aab") -> true
from collections import Counter
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
if not ransomNote:
return True
if len(ransomNote) > len(magazine):
return False
ransom_note_counter = Counter(list(ransomNote))
magazine_counter = Counter(list(magazine))
return all([
char in magazine_counter and ct <= magazine_counter[char]
for char, ct in ransom_note_counter.iteritems()
])
| true |
c4a8e21d1e7a821860d0626fcd95a1b7db7f9293 | Frankiee/leetcode | /graph_tree_bfs/1129_shortest_path_with_alternating_colors.py | 2,881 | 4.25 | 4 | # https://leetcode.com/problems/shortest-path-with-alternating-colors/
# 1129. Shortest Path with Alternating Colors
# Consider a directed graph, with nodes labelled 0, 1, ..., n-1. In this
# graph, each edge is either red or blue, and there could be self-edges or
# parallel edges.
#
# Each [i, j] in red_edges denotes a red directed edge from node i to node
# j. Similarly, each [i, j] in blue_edges denotes a blue directed edge from
# node i to node j.
#
# Return an array answer of length n, where each answer[X] is the length of
# the shortest path from node 0 to node X such that the edge colors
# alternate along the path (or -1 if such a path doesn't exist).
#
#
# Example 1:
#
# Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
# Output: [0,1,-1]
#
# Example 2:
#
# Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
# Output: [0,1,-1]
#
# Example 3:
#
# Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
# Output: [0,-1,-1]
#
# Example 4:
#
# Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
# Output: [0,1,2]
#
# Example 5:
#
# Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
# Output: [0,1,1]
#
#
# Constraints:
#
# 1 <= n <= 100
# red_edges.length <= 400
# blue_edges.length <= 400
# red_edges[i].length == blue_edges[i].length == 2
# 0 <= red_edges[i][j], blue_edges[i][j] < n
from collections import defaultdict
class Solution(object):
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
"""
:type n: int
:type red_edges: List[List[int]]
:type blue_edges: List[List[int]]
:rtype: List[int]
"""
ret = [float('inf')] * n
red_paths = defaultdict(list)
blue_paths = defaultdict(list)
for start, end in red_edges:
red_paths[start].append(end)
for start, end in blue_edges:
blue_paths[start].append(end)
current_step = 0
# (label, color) where 0: red, 1: blue
current_nodes = [(0, 0), (0, 1)]
visited = {(0, 0), (0, 1)}
while current_nodes:
next_current_nodes = []
for node in current_nodes:
current_label, current_color = node
ret[current_label] = min(ret[current_label], current_step)
next_color = 1 if current_color == 0 else 0
next_paths = blue_paths if current_color == 0 else red_paths
next_nodes = [
(next_label, next_color)
for next_label in next_paths[current_label]
if (next_label, next_color) not in visited
]
next_current_nodes.extend(next_nodes)
visited |= set(next_nodes)
current_nodes = next_current_nodes
current_step += 1
ret = [-1 if r == float('inf') else r for r in ret]
return ret
| true |
957535ca6554972ba06a5a925b12a787dcb177b7 | Frankiee/leetcode | /graph_tree_dfs/backtracking/282_expression_add_operators.py | 2,147 | 4.125 | 4 | # [Backtracking, Classic]
# https://leetcode.com/problems/expression-add-operators/
# 282. Expression Add Operators
# History:
# Facebook
# 1.
# Jan 23, 2020
# 2.
# Apr 1, 2020
# 3.
# May 10, 2020
# Given a string that contains only digits 0-9 and a target value, return all possibilities to
# add binary operators (not unary) +, -, or * between the digits so they evaluate to the target
# value.
#
# Example 1:
#
# Input: num = "123", target = 6
# Output: ["1+2+3", "1*2*3"]
# Example 2:
#
# Input: num = "232", target = 8
# Output: ["2*3+2", "2+3*2"]
# Example 3:
#
# Input: num = "105", target = 5
# Output: ["1*0+5","10-5"]
# Example 4:
#
# Input: num = "00", target = 0
# Output: ["0+0", "0-0", "0*0"]
# Example 5:
#
# Input: num = "3456237490", target = 9191
# Output: []
class Solution(object):
def dfs(self, num, target, curr_idx, curr_result, prev_num, curr_str, ret):
if curr_idx >= len(num):
if curr_result == target:
ret.append(curr_str)
return
for idx in range(curr_idx + 1, len(num) + 1):
new_num_str = num[curr_idx:idx]
new_num = int(new_num_str)
if idx == curr_idx + 1 or new_num_str[0] != '0':
# +
self.dfs(num, target, idx, curr_result + new_num, new_num,
curr_str + '+' + new_num_str, ret)
# -
self.dfs(num, target, idx, curr_result - new_num, -new_num,
curr_str + '-' + new_num_str, ret)
# *
self.dfs(num, target, idx, curr_result - prev_num + prev_num * new_num,
prev_num * new_num, curr_str + '*' + new_num_str, ret)
def addOperators(self, num, target):
"""
:type num: str
:type target: int
:rtype: List[str]
"""
ret = []
for idx in range(1, len(num) + 1):
new_num_str = num[:idx]
curr_result = int(new_num_str)
if idx == 1 or new_num_str[0] != '0':
self.dfs(num, target, idx, curr_result, curr_result, num[:idx], ret)
return ret
| true |
838ad53e6d388f2b042a685bea4895cf0891b5dc | Frankiee/leetcode | /multithreading/1114_print_in_order.py | 2,339 | 4.25 | 4 | # https://leetcode.com/problems/print-in-order/
# 1114. Print in Order
# History:
# Apple
# 1.
# Aug 10, 2019
# 2.
# Mar 19, 2020
# Suppose we have a class:
#
# public class Foo {
# public void first() { print("first"); }
# public void second() { print("second"); }
# public void third() { print("third"); }
# }
# The same instance of Foo will be passed to three different threads. Thread
# A will call first(), thread B will call second(), and thread C will call
# third(). Design a mechanism and modify the program to ensure that second()
# is executed after first(), and third() is executed after second().
#
#
# Example 1:
#
# Input: [1,2,3]
# Output: "firstsecondthird"
# Explanation: There are three threads being fired asynchronously. The input
# [1,2,3] means thread A calls first(), thread B calls second(), and thread
# C calls third(). "firstsecondthird" is the correct output.
#
# Example 2:
#
# Input: [1,3,2]
# Output: "firstsecondthird"
# Explanation: The input [1,3,2] means thread A calls first(), thread B
# calls third(), and thread C calls second(). "firstsecondthird" is the
# correct output.
#
#
# Note:
#
# We do not know how the threads will be scheduled in the operating system,
# even though the numbers in the input seems to imply the ordering. The
# input format you see is mainly to ensure our tests' comprehensiveness.
from threading import Lock
class Foo(object):
def __init__(self):
self.first_lock = Lock()
self.second_lock = Lock()
self.first_lock.acquire()
self.second_lock.acquire()
def first(self, printFirst):
"""
:type printFirst: method
:rtype: void
"""
# printFirst() outputs "first". Do not change or remove this line.
printFirst()
self.first_lock.release()
def second(self, printSecond):
"""
:type printSecond: method
:rtype: void
"""
self.first_lock.acquire()
# printSecond() outputs "second". Do not change or remove this line.
printSecond()
self.second_lock.release()
def third(self, printThird):
"""
:type printThird: method
:rtype: void
"""
self.second_lock.acquire()
# printThird() outputs "third". Do not change or remove this line.
printThird()
| true |
d90a04337c5ee794418cfa1f6e5fb129bbe039b1 | Frankiee/leetcode | /trie/208_implement_trie_prefix_tree.py | 2,064 | 4.15625 | 4 | # https://leetcode.com/problems/implement-trie-prefix-tree/
# 208. Implement Trie (Prefix Tree)
# History:
# Facebook
# 1.
# May 7, 2020
# Implement a trie with insert, search, and startsWith methods.
#
# Example:
#
# Trie trie = new Trie();
#
# trie.insert("apple");
# trie.search("apple"); // returns true
# trie.search("app"); // returns false
# trie.startsWith("app"); // returns true
# trie.insert("app");
# trie.search("app"); // returns true
# Note:
#
# You may assume that all inputs are consist of lowercase letters a-z.
# All inputs are guaranteed to be non-empty strings.
class TrieNode(object):
def __init__(self):
self.is_terminal = False
self.children = {}
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie_root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
curr = self.trie_root
for c in word:
if c not in curr.children:
curr.children[c] = TrieNode()
curr = curr.children[c]
curr.is_terminal = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
curr = self.trie_root
for c in word:
if c not in curr.children:
return False
curr = curr.children[c]
return curr.is_terminal
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
curr = self.trie_root
for c in prefix:
if c not in curr.children:
return False
curr = curr.children[c]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true |
fb4e34c477459204d46e5ed59b22406cf24eb148 | Frankiee/leetcode | /graph_tree_bfs/199_binary_tree_right_side_view.py | 1,930 | 4.21875 | 4 | # https://leetcode.com/problems/binary-tree-right-side-view/
# 199. Binary Tree Right Side View
# History:
# Facebook
# 1.
# Mar 15, 2020
# 2.
# Apr 22, 2020
# Given a binary tree, imagine yourself standing on the right side of it, return the values of
# the nodes you can see ordered from top to bottom.
#
# Example:
#
# Input: [1,2,3,null,5,null,4]
# Output: [1, 3, 4]
# Explanation:
#
# 1 <---
# / \
# 2 3 <---
# \ \
# 5 4 <---
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class SolutionDFS(object):
def _right_side_view(self, node, ret, curr_level):
if not node:
return
if len(ret) <= curr_level:
ret.append(node.val)
else:
ret[curr_level] = node.val
self._right_side_view(node.left, ret, curr_level + 1)
self._right_side_view(node.right, ret, curr_level + 1)
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
self._right_side_view(root, ret, 0)
return ret
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class SolutionBFS(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
to_do = [root]
ret = []
while to_do:
nxt_to_do = []
ret.append(to_do[-1].val)
for n in to_do:
if n.left:
nxt_to_do.append(n.left)
if n.right:
nxt_to_do.append(n.right)
to_do = nxt_to_do
return ret
| true |
992fe8cd658ec4c5725bc4f8a0239afa7516bb16 | CarYanG/leetcode_python | /question_6.py | 1,601 | 4.34375 | 4 | #-*-coding:utf-8-*-
__author__ = 'carl'
'''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"
'''
class Solution:
# @param {string} s
# @param {integer} numRows
# @return {string}
def convert(self, s, numRows):
str_list=list(s)
str_lists=[[]for i in range (numRows)]
str_len=len(str_list)
if numRows==1:
return s
else:
for i in range(str_len):
if i % (numRows+numRows-2)>=numRows:
str_lists[numRows-1-(i%(numRows+numRows-2))%(numRows-1)].append(str_list[i])
else:
str_lists[i%(numRows+numRows-2)].append(str_list[i])
for i in range(1,numRows):
str_lists[0].extend(str_lists[i])
return ''.join(str_lists[0])
s=Solution()
print s.convert('A',1)
'''
思路:
0 8
1 7 9
2 6 10
3 5 11
4 12
先不管中间的单个的数字,每一行都是除以8得到相同的余数,这个8就是行数的2倍减去2,即numRows+numRows-2
然后再看中间单个的数字,他们对8的余数都大于numRow,可以找到他们与所在行之间的关系,,
总之就是找规律求解
'''
| true |
341ec125e3f71f1f11d3f26bbeb561f028afb555 | vardhanvenkata/Text_to_speech | /Text_to_speech_with_UserInput.py | 486 | 4.125 | 4 | #import gtts module for text to speech conversion
import gtts
#import os to start the audio file
import os
#Taking input from user to convert it into speech
myText = input("Enter text to convert into Speech")
#language we want to use--In this case en--stands for english
language ='en'
output = gtts.gTTS(text=myText, lang=language, slow=False)
#This is used to save the audio file
output.save("Speech.mp3")
#Play the converted file
os.system("start Speech.mp3")
| true |
44e18c1ebbbdc6b57ec7ee5c309a15e840b923bf | mirzaakyuz/assignments | /first_functions.py | 307 | 4.125 | 4 | def add(a, b):
print(a + b)
add(3, 5)
def calculator(a, b, c):
if c == '*':
print(a * b)
elif c == '+':
print(a + b)
elif c == '-':
print(a - b)
elif c == '/':
print(a / b)
else: print('type valid caharacter!')
calculator(5, 2, '/') | false |
946c9af2f60d4c3049fb3b50b27b032595d10f09 | madhu20336/If-Else | /Oldest_age.py | 347 | 4.125 | 4 | age1=int(input("enter the age: "))
age2=int(input("enter the age: "))
age3=int(input("enter the age: "))
if age1 > age2 and age1 > age3:
print("oldest age is ",age1)
elif age2 > age3 and age2 > age1:
print("oldest age is",age2)
elif age3 > age1 and age3 > age2:
print("oldest age is",age3)
else:
print(age1,age2,age3,"equale age") | false |
1e8a9a3997617087585cdfcc320fda9467d43e28 | madhu20336/If-Else | /GreaterNumber.py | 214 | 4.1875 | 4 | num1=int(input("enter a number: "))
num2=int(input("enter a number: "))
if num1>num2:
print(num1,"is greater number")
elif num1<num2:
print(num2,"is greater number")
else:
print(num1,"is equal to",num2) | false |
9827dfe610c7a2bfecd5a7cd3be2598136bdbeb1 | stevemman/FC308-Labs | /Lab1/A3.py | 312 | 4.21875 | 4 | # Store information about our trapezoid.
base1 = 8
base2 = 7
height = 12
# Calculate the area for our trapezoid.
# Be careful on the order of operations, use brackets when needed.
area = ((base1 + base2) / 2) * height
# Print the area of the trapezoid to the user.
print("The area of the trapezoid is:", area)
| true |
dc08f31c3dfec4fb04bd855ba9e89faca3fd7490 | stevemman/FC308-Labs | /Lab6/Task4.py | 1,439 | 4.21875 | 4 | # One function per calculator operation.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
print("Welcome to the advanced calculator 9001")
# Infinite loop that will stop only when the user types "exit".
while True:
option = input("Select one of the options bellow.\n"
"(A)dd\n"
"(S)ubtract\n"
"(M)ultiply\n"
"(D)ivide\n"
"Or type \"exit\" to stop.\n"
">> ")
# This will break the loop and terminate the program.
if option.lower() == "exit":
break
# Ask the user to enter two numbers.
num1 = float(input("Please enter the first number: "))
num2 = float(input("Please enter the second number: "))
# The use of the lower() string function ensures that our program will accept both lowercase and uppercase letters.
if option.lower() == "a":
print("--", num1, "+", num2, "=", add(num1, num2))
elif option.lower() == "s":
print("--", num1, "-", num2, "=", subtract(num1, num2))
elif option.lower() == "m":
print("--", num1, "*", num2, "=", multiply(num1, num2))
elif option.lower() == "d":
print("--", num1, "/", num2, "=", divide(num1, num2))
else:
print("--ERROR! Invalid input.")
| true |
067d5d9a5069719dcfef2ac2cd3e6261803a62ae | stevemman/FC308-Labs | /Lab2/Task1.py | 308 | 4.4375 | 4 | # Ask the user for height and width of the rectangle in cm.
height = int(input("Enter the height: "))
width = int(input("Enter the width: "))
# Calculate and print the area of the rectangle.
print("The area of the rectangle with height", height, "cm and width", width, "cm is", height * width, "square cm")
| true |
d5b98d6df8f3bd89486c9442933019bb84452b44 | stevemman/FC308-Labs | /Lab3/A1.py | 344 | 4.25 | 4 | # Ask the user to enter their age.
age = int(input("Please enter your age :"))
# Depending on the age group display a different ticket price.
if age > 0 and age < 18:
print("The ticket costs : 1.50£")
elif age >= 18 and age < 65:
print("The ticket costs : 2.20£")
elif age >= 65 and age < 100:
print("The ticket costs : 1.20£")
| true |
981b94116fdc34e47d106acf9675d70ab16958c2 | qiaobilong/Python | /Learn_Python3_The_Hard_Way/ex22.py | 1,012 | 4.25 | 4 | """
1.print:打印输出
格式化print("格式化符号" %(传入的参数))
str = "the length of (%s) %d" %('runoob',len('runoob'))
print(str)
转:http://www.runoob.com/w3cnote/python3-print-func-b.html
formatter.format('one','two')
print("{:.2f}".format(3.1415926535))
>>> 3.14
转:http://www.runoob.com/python/att-string-format.html
2.注释:
#、'''......'''、三个双引号
3.数学运算符:
+、-、*、/、%、>、<、=
4.f"Hello {somevar}" 格式化
5.四舍五入:round(1.7654321)
6.转义符(\)
7.input():接收用户输入的信息(默认文本型),int(input())将输入的信息转化为数值型
8.argument variable 参数变量
9.for sys import argv 导入模块
10.fo = open(file)
11.fo.read()
12.close、readline、truncate(清空文件)、write、seek(0)
13.from op.path import exists
exists(file):file存在返回True,否则返回False
14.def 函数名(*argv):
函数体
return
"""
| false |
b562066ca6fefddfeef8728b7ec9834a8f3e52b1 | torz/awstest | /interview.py | 627 | 4.1875 | 4 |
def isValid(s):
parenthesis = 0
for i in s:
if i == '(':
parenthesis += 1
if i == ')':
parenthesis -= 1
if parenthesis < 0:
return False
if parenthesis == 0:
return True
else:
return False
if __name__ == '__main__':
print(isValid('(test)'))
print(isValid('((test))'))
print(isValid('()test()'))
print(isValid(')test('))
print(isValid('(test'))
'''
create a method that returns true/false
check for valid parenthesis
() is valid
()() is valid
(()) is valid
)( is not valid
(( is not valid
)) is not valid
'''
| true |
69f64f9ad1145969985f3d371ef68d14ccfb69c6 | KristinaKeenan/PythonWork | /Lab9/Lab9.py | 2,367 | 4.15625 | 4 | #Kristina Keenan
#4/8/15
#The purpose of this program is to take an inputed phrase and check to see if it spelled correctly.
def wordIndex():
'''This function reads a file and creates a list of words from it.'''
wordIndex1 = open("words1.txt", "r")
#wordIndex2 = open("words2.txt","r")
words1 = wordIndex1.readlines()
#words2 = wordIndex2.readlines()
return words1
def listMaker(wordsCheck):
'''This function takes the inputed phrases and creates a list out of the words.'''
wordsList = wordsCheck.split(" ")
return wordsList
def suggestions(mispelledWord):
'''This function sees if an iterance of a mispelled word is erroneous because it is two correct words without a space in between them.
If so, then the function prints a suggested way to fix the problem.'''
words = wordIndex()
#This sees splits the misspelled word into two words that are spelled correctly
for i in range(len(mispelledWord)):
if mispelledWord[:i] + "\n" in words and mispelledWord[i:] in words:
print("Here's a suggestion: \n",mispelledWord[:i],mispelledWord[i:])
def spellCheck(wordsCheck):
'''This function checks to see if the words in the phrase are in the word list or are mispelled, and then
calls functions or prints phrases accordingly.'''
wordsList = listMaker(wordsCheck)
words1 = wordIndex()
check = 0
#These see if all the words are correct, or if there are some correct/incorrect
for i in wordsList:
if i + "\n" in words1:
check = check + 1
if check == len(wordsList):
print("This entire phrase is correct.")
else:
for i in wordsList:
if i + "\n" in words1:
print(i,"is spelled correctly.")
check = check + 1
else:
print(i,"may be mispelled.")
#this checks to see if the misspelled words are two words without a space inbetween them.
suggestions(i + "\n")
tryAgain = input("Enter more words or 'quit' to quit:")
if tryAgain != "quit":
spellCheck(tryAgain)
def main():
'''This is the main function, which accepts an inputed phrase and calls the spellCheck function.'''
wordsCheck = input("Words to spellcheck:")
spellCheck(wordsCheck)
main()
| true |
cbe0b0eddf54099de5092399ff15be71a1058045 | KristinaKeenan/PythonWork | /3_23_15.py | 1,569 | 4.15625 | 4 | def vowelCheck(englishString):
vowels = "AEIOUaeiou"
if englishString[0] in vowels:
return True
else:
return False
def vowelGet(englishString):
pigLatin = englishString + "way"
return pigLatin
def consonantGet(englishString):
newWord = ""
vowels = "AEIOUaeiou"
charend = False
for aChar in englishString:
if aChar not in vowels and charend == False:
newWord = newWord + aChar
else:
charend = True
sliceOff = len(newWord)
pigLatin = englishString[sliceOff:len(englishString)] + newWord + "ay"
return pigLatin
def main():
englishString = input("What do you want to translate?")
if vowelCheck(englishString):
newphrase = vowelGet(englishString)
else:
newphrase = consonantGet(englishString)
print("Your word:","\n",englishString)
print("Translated word:","\n",newphrase)
main()
#algorithm:
#first you create a function that calls for input of a string, then call a function that translates that
#function into pig latin. This function first determines if the string begins with a vowel or a
#consonant. There is an if statement that prints the string from the second letter to the last using a slice,
#then concates the first letter to the end of that using a string and then adds the string "ay".
#If it begins with a vowel, then the string "way" is concated to the end of the string.
#myString = "This class is awesome"
#stringList = "myString.split(" ")
#stringList is now: ["This","class","is","awesome"]
| false |
519bc18cdbb83f4466852f1ec5bdf6e9d2eecacc | KristinaKeenan/PythonWork | /2_4_15.py | 916 | 4.15625 | 4 | #Kristina Keenan
#2/5/15
#The purpose of this program is to drawn increasingly lighter and larger cocentric cirlces
#import and set up turtle
import turtle
wn = turtle.Screen()
square = turtle.Turtle()
#write a statement to determine how many squares
squareNumber = int(input("How many squares are you drawing?"))
#intialize the variables for the colors and length
red = 0
green = 0
blue = 0
length = 1
square.speed(0)
#create the loop
for i in range (squareNumber):
#squares
square.pendown()
square.forward(length)
square.left(90)
square.forward(length)
square.left(90)
square.forward(length)
square.left(90)
#redefine the length
length = (length + 1)
#color
square.color(red, green, blue)
red = (red + 1/squareNumber)
green = (green + 1/squareNumber)
blue = (blue + 1/squareNumber)
| true |
0b40a9765c9ed4c480c868384d1195cbe32d3578 | wiktorfilipiuk/pythonML | /myImplementation/myFunctions/distance.py | 709 | 4.40625 | 4 | def distance(x_start, x_end, n=1):
""" x_start, x_end - 2 vectors between which distance is to be measured
n - order of the measured distance according to Minkowski distance's definition
"""
if len(x_start) != len(x_end):
print("[ERROR] - Inconsistent dimensions of input vectors!")
result = -1
elif n < 1:
print("[ERROR] - Order 'n' has to be >= 1!")
result = -1
else:
tmp = [abs(x_end[i] - x_start[i]) for i in range(len(x_start)) ]
tmpPower = [value**n for value in tmp]
tmpSum = sum(tmpPower)
result = tmpSum**(1/n)
return(result)
def euclideanDistance(x_start, x_end):
"""
Function created to increase readability in external files.
"""
return(distance(x_start, x_end, n=2)) | true |
7032638ce55e5ab5c99abe7f74e4a2960a5c6303 | Researcher-Retorta/Python_Data_Science | /Week_01/Objects_and_map().py | 774 | 4.34375 | 4 | # An example of a class in python
class Person:
department = 'School of Information' #a class variable
def set_name(self, new_name): #a method
self.name = new_name
def set_location(self, new_location):
self.location = new_location
person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI, USA')
print('{} live in {} and works in the department {}'.format(person.name, person.location, person.department))
# Here's an example of mapping the min function between two lists.
store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
print(cheapest)
# Now let's iterate through the map object to see the values.
for item in cheapest:
print(item)
| true |
a91be3d64b59eb7b943bff7fce7b38ea7ab6e0a3 | Ruths2/curso-python | /ex005.py | 295 | 4.125 | 4 | n = int (input('Digite um número:'))
a = n-1
s = n+1
print ('Avaliando o número {}, seu antecessor é {}, e o seu sucessor é {}!' .format(n, a, s))
n = int (input('Digite um número:'))
print ('Avaliando o número {}, seu antecessor é {}, e o seu sucessor é {}!' .format(n, n-1, n+1))
| false |
76ffcabab0a6d07638a0c77a0553c5be43683b36 | dodonut/MIT-opencourseware | /Introduction-to-python-and-computer-science/6.0001-introduction-to-computer-science/ps1/ps1c_Finding_the_right_ammount_to_save.py | 1,124 | 4.15625 | 4 | portion_down_payment = 0.25
r = 0.04
total_cost = 1000000
semi_annual_raise = .07
current_savings = 0
three_years = 36
down_payment = total_cost * portion_down_payment
starter_salary = float(input("Enter your starting salary: "))
annual_salary = starter_salary
n_months = 0
n_steps = 0
able_to_pay = True
low = 0
high = 10000
epsilon = 100
while abs(down_payment - current_savings) > epsilon:
current_savings = 0
n_months = 0
annual_salary = starter_salary
m = (low + high) / 2.0
portion_saved = round(m/(annual_salary/12.0), 4)
while current_savings < down_payment and n_months < three_years:
current_savings += (current_savings * r + portion_saved * annual_salary) / 12.0
n_months += 1
if n_months % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
if current_savings < down_payment:
low = m
else:
high = m
n_steps += 1
if portion_saved > 1:
print("It is not possible to pay the down payment in three years.")
else:
print("Best savings rate: " , portion_saved)
print("Steps in bisection search: ", n_steps)
| false |
4e239504c88dfcefbb37eeca6dfeb6987666a6dd | shubee17/HackerEarth | /Basic_IO/Riya_in_AngleHack.py | 714 | 4.21875 | 4 | """
Riya is getting bored in angelhack then Simran came with a game in which there is given a number N . If the number is divisible by 3 then riya has to print Angel and if number is divisible by 5 then she has to print Hack and if divisible by both then she has to print AngelHack! .If N does not satisfy any condition print the number as it is .Help Riya in printing the result.
INPUT FORMAT :
Given a number N.
OUTPUT FORMAT :
Print the string as per the condition.
CONSTRAINTS:
1<=N<=109
SAMPLE INPUT
6
SAMPLE OUTPUT
Angel
"""
N = raw_input()
if int(N)%3 == 0 and int(N)%5 == 0:
print 'AngelHack!'
elif int(N)%3 == 0:
print 'Angel'
elif int(N)%5 == 0:
print 'Hack'
else:
print int(N)
| true |
6c014ebe86e6aa10129f7081674ed8435a420b11 | kinsanpy/LearnPythonTheHardWay | /ex3.py | 786 | 4.5 | 4 | print "I will now count my chickens:"#print a line
print "Hens", 25 + 30 / 6# print a world and do the math
print "Roosters", 100 - 25 * 3 % 4#the same as above
print "Now I will count the eggs:"# print a line
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6# print the result of the math
print "Is it true that 3 + 2 < 5 - 7?"# print a line
print 3 + 2 < 5 - 7# print the logical result of the comparison
print "What is 3 + 2?", 3 + 2# print a question and do the math
print "What is 5 - 7?", 5 - 7# same as above
print "Oh, that's why it's False."# print a line
print "How about some more."# same as above
print "Is it greater?", 5 > -2# print a question and do a comparison
print "Is it greater or equal?", 5 >= -2# same as above
print "Is it less or equal?", 5 <= -2# same as above
| true |
fcffd8e4d4aa2b0bfc051a68bf56a3436aa6e08d | 340730/chicken | /Polynomial_Class.py | 921 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
In this script we will define a class called Polynomial.
"""
class Polynomial:
def __init__(self, coefficients):
self.coeff = coefficients
def degree(self):
return len(self.coeff) - 1
def __str__(self):
s = ''
for i in range(len(self.coeff)):
s += f'({self.coeff[i]})x^{self.degree() - i} +'
return s[:-1]
def __call__(self, x):
value = 0
for i in range(len(self.coeff)):
value += self.coeff[i]*(x**(self.degree() - i))
return value
def derivative(self):
df = []
for i in range(len(self.coeff) - 1):
df.append(self.coeff[i]*(self.degree() - i))
return Polynomial(df)
"""
from Polynomial_Class import *
f = Polynomial([7,0,-1,10])
f.__str__()
f(2)
df = f.derivative()
print(df)
""" | false |
2d4f702901ba51248dd16b0edae00d106087106d | RyCornel/C.S.-1.0-Lists---Loops-Tutorial- | /lists_loops.py | 753 | 4.15625 | 4 | #Q1
songs =["ROCKSTAR", "Do It", "For the Night"]
print(songs[1])
#Q2
print(songs[0:3])
print(songs[1:3])
#Q3
songs[0] = "Dynamite"
print(songs)
songs[2] = "Everything I Wanted"
print(songs)
#Q4
songs.append("Roman Holiday")
songs.extend(["Do What I Want"])
songs.insert(3, "3:15")
print(songs)
songs.pop(0)
del songs[1]
print(songs)
#Q5
for song in songs:
print(song)
#Option 1, prints out the whole list, as is.
for i in range(len(songs)):
print(songs[i])
#Option 2, prints out a range within the list of songs. Eg: it's possible to print out the third and fourth songs, specificially.
#Q6
animals = ["Stingray", "Tiger", "Hawk"]
animals.append("Dolphin")
print(animals[2])
del animals[0]
for animal in animals:
print(animals) | true |
aaee654bec20080a90564db40433e0bfed270110 | Torrontogosh/MITx-6.00.1x | /Unit 01/Finger Exercise 01.py | 589 | 4.15625 | 4 | # This exercise was written with the assumption that none of the variables defined at the top would be over 1000. It simply tries to place the lowest odd number into the variable "lowest_number", and either prints that number out or prints a message that there are no odd numbers.
x = 10
y = 30
z = 14
lowest_number = 1000
if x%2 != 0:
lowest_number = x
if y%2 != 0 and y < lowest_number:
lowest_number = y
if z%2 != 0 and z < lowest_number:
lowest_number = z
if x%2 == 0 and y%2 == 0 and z%2 == 0:
print('There are no odd numbers.')
else:
print(lowest_number)
| true |
99020e3df23ff72861b7a51f64eb80eb908e5112 | ppuczka/python_for_devOps_workshop_1 | /game.py | 2,805 | 4.125 | 4 | import random
computer_moves = {
1 : "rock",
2 : "papper",
3 : "scissors"
}
def printResults(arg1, arg2):
print("You: " + arg1)
print("Computer: " + arg2)
def rock(arg):
if arg == "rock":
print("tie")
elif arg == "papper":
print("you lost")
else:
print("you won")
def papper(arg):
if arg == "rock":
print("you won")
elif arg == "papper":
print("tie")
else:
print("you lost")
def scissors(arg):
if arg == "rock":
print("you lost")
elif arg == "papper":
print("you won")
else:
print("tie")
def computerInput():
r = random.randint(1, 3)
return computer_moves.get(r)
user_choice = input("rock / papper / scissors: ")
while user_choice.lower() != "exit":
computer_choice = computerInput()
if user_choice == "papper":
if computer_choice == "papper":
printResults(user_choice, computer_choice)
print("Tie")
user_choice = input("rock / papper / scissors: ")
elif computer_choice == "rock":
printResults(user_choice, computer_choice)
print("You Lost")
user_choice = input("rock / papper / scissors: ")
else:
printResults(user_choice, computer_choice)
print("You Won !!!!!")
user_choice = input("rock / papper / scissors: ")
elif user_choice == "scissors":
if computer_choice =="rock":
printResults(user_choice, computer_choice)
print("You lost")
user_choice = input("rock / papper / scissors: ")
elif computer_choice == "papper":
printResults(user_choice, computer_choice)
print("You won !!!!!")
user_choice = input("rock / papper / scissors: ")
else:
printResults(user_choice, computer_choice)
print("Tie")
user_choice = input("rock / papper / scissors: ")
elif user_choice == "rock":
if computer_choice == "papper":
printResults(user_choice, computer_choice)
print("You lost")
user_choice = input("rock / papper / scissors: ")
elif computer_choice == "rock":
printResults(user_choice, computer_choice)
print("Tie")
user_choice = input("rock / papper / scissors: ")
else:
printResults(user_choice, computer_choice)
print("You Won !!!!!")
user_choice = input("rock / papper / scissors: ")
elif user_choice == "exit":
break
else:
print("Wrong choice")
user_choice = input("rock / papper / scissors: ")
| false |
131f08ab84fe9783f690d016104beedd8a490ee4 | Maximizer07/python-practice | /practice01_extra/task2.py | 338 | 4.1875 | 4 | def fast_pow(x,y):
pow=1
while y>0:
if (y==1):
return pow*x
if (y%2==1):
pow*=x
x*=x
y//=2
return pow
def fast_pow_test():
for x in range(1,101):
for y in range(1,101):
assert fast_pow(x, y) == x ** y
print("Успешно")
fast_pow_test() | false |
ec6538eaa41e598c2f801f366d95668b2fa698f7 | deepdhar/Python-Programs | /Basic Programs/count_vowels_consonants.py | 288 | 4.125 | 4 | #program to count vowels and consonants of a string
str1 = input()
vowels = "aeiou"
count1 = 0
count2 = 0
for ch in str1.lower():
if ch>='a' and ch<='z':
if ch in vowels:
count1 += 1
else:
count2 += 1
else:
continue
print("Vowels: {}\nConsonants: {}".format(count1,count2)) | true |
0e522a99d76e46d378727712343dcfc0427de090 | comptoolsres/Class_Files | /Examples/square.py | 295 | 4.3125 | 4 | #!/usr/bin/env python
# square.py: Demo of argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=float)
args = parser.parse_args()
print(f"The square of {args.square} is {args.square**2}")
| true |
c100904b509cdd1fca824a4f101becd649b91604 | cursoAlgoTradingRTS/PAT | /Clase 2/ejercicios/ejercicio2-1.py | 2,019 | 4.28125 | 4 | # coding=utf-8
'''
Ejercicio 2.1. Implementar algoritmos que resuelvan los siguientes problemas:
a) Dados dos números, imprimir la suma, resta, división y multiplicación de ambos.
b) Dado un número entero n, imprimir su tabla de multiplicar.
c)Implementar un algoritmo que, dado un numero entero n, permita calcular su
factorial.
'''
def sumaDosNumeros(num1, num2):
return num1 + num2
def restaDosNumeros(num1, num2):
return num1 - num2
#Ojo que esta division devuelve el valor entero de la misma, si se quiere obtener el valor con decimales hay que convertir los numeros a punto flotante
def dividir(dividendo, divisor):
return dividendo/divisor
def multiplicar(num1, num2):
return num2*num1
def imprimirOperacionesMatematicas(num1, num2):
print "Suma " + str(sumaDosNumeros(num1, num2))
print "Resta " + str(restaDosNumeros(num1, num2))
print "Division " + str(dividir(num1, num2))
print "Multiplicacion " + str(multiplicar(num1, num2))
imprimirOperacionesMatematicas(25,4)
def tablaMultiplicar(numero):
for x in range(10):
multiplo = x+1
print str(multiplo) + " x " + str(numero) + " = " + str(multiplo*numero)
tablaMultiplicar(8)
# resolucion en forma iterativa
def factorialIterativo(numero):
factorial = 1
for i in range(1, numero + 1, 1):
factorial = factorial * i
return factorial
# resolucion en forma recursiva
def calcularFactorial(numero):
if (numero == 0 or numero == 1):
return numero
else:
return numero * (calcularFactorial(numero - 1))
print calcularFactorial(1)
print calcularFactorial(3)
print calcularFactorial(5)
print calcularFactorial(8)
print calcularFactorial(9)
print calcularFactorial(12)
print calcularFactorial(15)
print calcularFactorial(100)
print factorialIterativo(1)
print factorialIterativo(3)
print factorialIterativo(5)
print factorialIterativo(8)
print factorialIterativo(9)
print factorialIterativo(12)
print factorialIterativo(15)
print factorialIterativo(100)
| false |
f8b165301c9931121105e87cc13f486c6d1fcd15 | EricOHansen5/Algorithm-Challenges | /find_max_len of valid parenthesis.py | 1,586 | 4.21875 | 4 | #https://practice.geeksforgeeks.org/problems/valid-substring/0
#------------------------
#Given a string S consisting only of opening and closing parenthesis 'ie '(' and ')', find out the length of the longest valid substring.
#NOTE: Length of smallest the valid substring ( ) is 2.
#Input
#The first line of input contains an integer T denoting the number of test cases. Then T test cases follow.
#The first line of each test case contains a string S consisting only of ( and ).
#Output
#Print out the length of the longest valid substring.
#Examples
#Input
#4
#(()(
#()()((
#((()()())))
#()(())(
#Output
#2
#4
#10
#6
#------------------------
def find_max_len():
#get string input "())()()()(()))(()((((()))()()()())))"
arr = input()
#stack of indexes, stores the indexes of the '(' chars
stack_index = []
stack_index.append(-1)
#return value
final_out = 0
#traverse all chars of array
for i in range(len(arr)):
#checks if current index in the array is equal to '(' char, if so append to index stack
if arr[i] == '(':
stack_index.append(i)
else:
#else char is ')'
#which pops the last index off to remove last index of '(' char
stack_index.pop()
#if ')' char received and stack is not empty stores max between current index
# and the last substring end char index
if len(stack_index) != 0:
final_out = max(final_out, i - stack_index[-1])
else:
#if stack_index length equals 0 append end character substring index
stack_index.append(i)
return final_out
t = int(input())
for _ in range(t):
print(find_max_len()) | true |
607c1a638a2e5898b0a5f9de93c75e1599e46e86 | kevinelong/PM_2015_SUMMER | /StudentWork/RachelKlein/list_to_string.py | 740 | 4.4375 | 4 | one_string = ['Jay']
two_strings = ['Stephen', 'Dar']
three_strings = ['Reina', 'Ollie', 'Rachel']
# This prints a list of items as a string with the Oxford comma.
# If I could do this method again I would make it a lot simpler so the same code would handle any length of list.
def list_to_string(list):
length = len(list)
if length == 2:
return str(list[0]) + " and " + str(list[1])
elif length >= 3:
new_string = ''
for x in xrange(length):
new_string += (str(list[x])) + ", "
new_string += "and " + str(list[1])
return new_string
else:
return str(list[0])
print list_to_string(one_string)
print list_to_string(two_strings)
print list_to_string(three_strings) | true |
11af401446614bff9bd92c1eff3e63cfac1b1e34 | kevinelong/PM_2015_SUMMER | /StudentWork/JayMattingly/PMSchoolWork/Code_challenges/python_files/For_while_practice.py | 1,685 | 4.28125 | 4 | #Write a program that will bring out the time every second for 10 seconds.(must use a loop of some kind)
# import time #imports time method
#
# count = 0 #set the count to start to 0
#
# while True: #begins looking if statement is true
# if count < 10: #looks at the count, if less then continue into loop
# count += 1 #add 1 to current count
# print time.localtime() #prints the local time
# time.sleep(1) #wait 1 second before continuing with loop
# else: #if loop isn't true
# break #breaks loop
#
#
#
import time #imports time method
import random #imports random method
count = 0 #set the count to start to 0
while True: #begins looking if statement is true
if count < 5: #looks at the count, if less then continue into loop
count += 1 #add 1 to current count
result = random.randint(1, 10) #stores random integer into result
print result #prints the result
time.sleep(0.25) #makes loop wait 0.25 seconds
else: #if loop isn't true
print "Done!" #prints Done!
break #breaks loop
| true |
8ce79891fdf8b62f72757f585619a32619b6b5e9 | lytvyn139/udemy-complete-python3-bootcamp | /26-nested-statements.py | 1,459 | 4.375 | 4 | x = 25
def printer():
x = 50
return x
print(x) #25
print(printer()) #50
"""
LEGB Rule:
L: Local — Names assigned in any way within a function (def or lambda), and not declared global in that function.
E: Enclosing function locals — Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.
B: Built-in (Python) — Names preassigned in the built-in names module : open, range, SyntaxError,...
"""
# x is local here:
f = lambda x:x**2
#################
name = 'This is a global name'
def greet():
name = 'Sammy'
def hello():
print('Hello '+name)
hello()
greet() #hello Sammy
#################
name = 'This is a global name'
def greet():
#name = 'Sammy'
def hello():
print('Hello '+name)
hello()
greet() #hello This is a global string
#################
name = 'This is a global name'
def greet():
name = 'Sammy'
def hello():
name = 'LOCAL'
print('Hello '+name)
hello()
greet() #hello LOCAL
x = 50
def func(x):
#global x #only if you know what you're doint
print('This function is now using the global x!')
print('Because of global x is: ', x)
x = 2
print('Ran func(), changed global x to', x)
print('Before calling func(), x is: ', x)
func(10)
print('Value of x (outside of func()) is: ', x) | true |
e7cbf1db6c2087acf014cfec0352756fdc566ffe | pr0videncespr0xy/Providence | /Guessing Game.py | 1,002 | 4.3125 | 4 | #Import random module
import random
#Print out greeting
print("Welcome to the guessing game!!!")
#set number of guesses and define a variable for the user winning
number_of_guess = 3
user_won = False
#Set answer
correct_answer = random.randint(1, 10)
#set number of guesses and set assign variable as integer
while number_of_guess > 0 :
input("Guess my number : ")
number_of_guess = int(number_of_guess)
#set logic for guessing game
if number_of_guess == correct_answer:
print("congratulations!!!")
user_won = True
break
elif number_of_guess > correct_answer:
print("you guessed too high")
elif number_of_guess < correct_answer:
print("you guessed too low")
#set the negation of the number of guesses after every attempt
number_of_guess -= 1
#set the dialogue of the end result
if user_won == True:
print("congratulations you have won")
else:
print("Sorry, but you lose.")
| true |
8bb1001861c4764b5d72abf72af6e3596d920b2b | milosmatic1513/Python-Projects | /py_rot13_ergiasia3/python_rot13.py | 1,006 | 4.15625 | 4 | import rot13_add
final="";
while True:
ans=raw_input("Would you like to read from a file or directly input the text? (file/text)")
if (ans=="file"):
while True:
try:
input_file=raw_input("Input file to read from :(type 'exit' to exit) ")
if (input_file=="exit"):
break
inp=open(input_file,"r")
break
except:
print "file not found"
break
elif(ans=="text"):
inp=raw_input("Input text :(type 'exit' to exit) ")
break
if (inp!="exit"):
while True:
ans=raw_input("Whould you like to encrypt or decrypt in rot13? (en/de) :")
if(ans=="en"):
for line in inp:
final+=rot13_add.encode_rot13(line);
print final
break
elif(ans=="de"):
for line in inp:
final+=rot13_add.decode_rot13(line);
print final
break
while True:
ans1=raw_input("would you like to save this text?(y/n)")
if (ans1=="y"):
saves=open("saves.txt","a")
final_save="saved text("+ans+"):\n"+final+"\n"
saves.write(final_save)
break
elif(ans1=="n"):
break | true |
d68e8f5473bb57678fde2bd302351690f17d1992 | bethbarnes/hashmap-implementation | /linkedlist.py | 1,812 | 4.15625 | 4 | #!/usr/bin/env python
#---------SOLUTION----------#
#define Node class
class Node:
def __init__(self, key=None, val=None):
self.next_node = None
self.key = key
self.val = val
#define Linked List class
class Linked_List:
def __init__(self):
self.head = None
#add new node to head
def add_LL_node(self, key, val):
new_node = Node(key, val)
if self.head is not None:
previous_head = self.head
new_node.next_node = previous_head
self.head = new_node
#iterate through Linked List to find node
def find_node(self, key):
curr_node = self.head
while curr_node:
if curr_node.key == key:
return curr_node.val
curr_node = curr_node.next_node
raise KeyError(f'key ({key}) not found')
#--------TESTS--------#
def main():
print('test - creates nodes with passed in key, value and next properties')
new_node = Node('John', 22)
assert new_node.key == "John"
assert new_node.val == 22
assert new_node.next_node is None
print('test - initializes empty Linked List')
my_LL = Linked_List()
assert my_LL.head is None
print('test - can add nodes to Linked List')
my_LL.add_LL_node('Jane', 24)
assert my_LL.head.key == 'Jane'
my_LL.add_LL_node('Robert', 36)
my_LL.add_LL_node('Jason', 35)
assert my_LL.head.key == 'Jason'
assert my_LL.head.next_node.key == 'Robert'
assert my_LL.head.next_node.next_node.key == 'Jane'
print('test - can find nodes in Linked List by key')
assert my_LL.find_node('Robert') == 36
assert my_LL.find_node('Jason') == 35
assert my_LL.find_node('Jane') == 24
print('test - throws error if key not found in Linked List')
try:
my_LL.find_node('Monica')
except KeyError as e:
assert e.args[0] == 'key (Monica) not found'
if __name__ == '__main__':
main()
| true |
34b6cb57b77cae82e4beff1b8f0e968a3136abac | vijaymaddukuri/python_repo | /training/DataStructures-Algorithm/Tree/13root_to_leaf_sum_equal.py | 1,380 | 4.34375 | 4 | """
For example, in the above tree root to leaf paths exist with following sums.
21 –> 10 – 8 – 3
23 –> 10 – 8 – 5
14 –> 10 – 2 – 2
So the returned value should be true only for numbers 21, 23 and 14.
For any other number, returned value should be false.
"""
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def hasPathSum(node, s):
# Return true if we run out of tree and s = 0
if node is None:
return (s == 0)
else:
ans = 0
# Otherwise check both subtrees
subSum = s - node.data
# If we reach a leaf node and sum becomes 0, then
# return True
if (subSum == 0 and node.left == None and node.right == None):
return True
if node.left is not None:
ans = ans or hasPathSum(node.left, subSum)
if node.right is not None:
ans = ans or hasPathSum(node.right, subSum)
return ans
# Driver program to test above functions
s = 21
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.right = Node(5)
root.left.left = Node(3)
root.right.left = Node(2)
if hasPathSum(root, s):
print("There is a root-to-leaf path with sum %d" % (s))
else:
print("There is no root-to-leaf path with sum %d" % (s)) | true |
7e4826bf346984ffe46cf8fb648c11c848be6c53 | vijaymaddukuri/python_repo | /machine_learning/numpy_modules/index_100_element.py | 336 | 4.1875 | 4 | """
Index of the 100th Element
Consider an (11,12) shape array. What is the index (x,y) of the 100th element? Note: For counting the elements, go row-wise.
For example, in the array:
[[1, 5, 9],
[3, 0, 2]]
the 5th element would be '0'.
"""
import numpy as np
array1 = np.array(range(1, 11*12+1))
print(np.unravel_index(99, (11,12))) | true |
fc59b8eae3348d30248002695e31acef2668dd9d | edsakamoto/python-guanabara | /mundo03/ex085.py | 574 | 4.125 | 4 | """
crie um programa onde o usuario possa digitar sete valores numericos e cadastre os em uma lista unica que mantenha separados os valores pares e impares. no final mostre os valores pares e impares em ordem crescente
"""
num = [[],[]]
valor = 0
for c in range(0,7):
valor = int(input('Digite um valor: '))
if valor % 2 == 0:
num[0].append(valor)
else:
num[1].append(valor)
print('-'*30)
print(f'Numeros digitados: {valor} ')
num[0].sort()
num[1].sort()
print(f'Numeros digitados par: {num[0]} ')
print(f'Numeros digitados impar: {num[1]} ')
| false |
f1ce49c2917232ca0071545289ed4fbf96a9a07f | olegbei/publicrepository | /hw_1_1.py | 1,404 | 4.15625 | 4 | first_name = input('Please enter your first name ')
second_name = input('Please enter your second name ')
a = "Hello"
print("{0} {1} {2}".format(a, first_name, second_name))
birthday = int(input('Please enter your day of birth '))
birth_month = int(input('Please enter your birth month '))
birth_year = int(input('Please enter your birth year '))
amount_of_years = 2019 - birth_year - 1
amount_of_months = (amount_of_years * 12) + birth_month
#знаходимо кількість днів, яка лишилась до кінця першого року після народження
amount_of_days_till_the_end_the_first_year = 365 - ((30 - birthday) + (12 - birth_month)*30)
#знаходимо кількість років, які лишились до початку курсу
number_of_years_till_the_start = 2019 - birth_year - 1
#тут знаходимо кількість днів до 01.01.2019 і додаємо 31 день нового року
amount_of_days_till_the_start = number_of_years_till_the_start * 12 * 30 + amount_of_days_till_the_end_the_first_year + 31
print("You are", amount_of_years)
print("You've been living for", amount_of_months, 'months')
print("You've been living for", amount_of_days_till_the_start, "days or", number_of_years_till_the_start * 12 + 1, 'full months or', number_of_years_till_the_start , "full years till the start of this lesson" )
| false |
c6001e535885859595c81fc65debcd6e0b2c0e8d | chasevanblair/mod10 | /class_definitions/customer.py | 1,989 | 4.25 | 4 | class Customer:
"""
Program: customer.py
Author: Chase Van Blair
Last date modified: 7/5/20
The purpose of this program is to get used to making classes
and overriding built in functions
"""
def __init__(self, id, lname, fname, phone, address):
"""
constructor for the Customer object
:param id: Id of customer
:param lname: Last name of customer
:param fname: first name of customer
:param phone: phone number of customer
:param address: address of customer
"""
if not isinstance(id, int):
raise AttributeError
self.customer_id = str(id)
self.last_name = lname
self.first_name = fname
self.phone_number = str(phone)
self.address = address
def __str__(self):
"""
makes a string output of the data in Customer object
:return: string of data
"""
return ("ID: %s, Name: %s %s, Phone #: %s, Address: %s" % (self.customer_id, self.first_name, self.last_name,
self.phone_number, self.address))
def __repr__(self):
"""
the str method but returns the variable value of the string not just a straight string
:return: variable of string output
"""
return ("ID: %s, Name: %s %s, Phone #: %s, Address: %s" % (self.customer_id, self.first_name, self.last_name,
self.phone_number, self.address))
def display(self):
"""
prints out the string function for easy access
:return:
"""
print(self.__str__())
if __name__ == "__main__":
customer1 = Customer(333, "pob", "chad", 4144141141, "333 n street st")
customer1.display()
customer2 = Customer("monkey", "dope", "not", 54555555555, "71628654871245 space St.")
customer2.display()
# constructor raised exception
| true |
36b78478c176c74b8e2bd686ce633668a203601e | deep56parmar/Python-Practicals | /practical9.py | 407 | 4.125 | 4 | class Vol():
"""Find volume of cube and cylinder using method overloading."""
def __init__(self):
print("")
def volume(self,data1 = None, data2 = None):
if data1 and not data2:
print("Volume of cube is ", data1**3)
elif data1 and data2:
print("volume of cylinder is ", 3.14*data1*data1*data2)
object = Vol()
object.volume(12)
object.volume(10,11)
| true |
058eaad4b5418a027282d45071f9a23b3655e9b7 | ThomasBaumeister/oreilly-intermediate-python | /warmup/vowels.py | 236 | 4.25 | 4 | #!/usr/bin/python3
import scrabble
vowels="aeiou"
def has_all_vowels(word):
for vowel in vowels:
if vowel not in word:
return False
return True
for word in scrabble.wordlist:
if has_all_vowels(word):
print (word)
| true |
e5e5ba6956c0133d5b5632fe7df04e3d9cae17b6 | rebht78/Python-Exercises | /exercise29.py | 527 | 4.34375 | 4 | """
We are used to list now, let's introduce some more functions to list.
So moving further,
String is also a kind of list. Because String is a collection of
characters.
If string in python is a collection of characters (list), then
we can use all the techniques of list with strings too.
Let's see an example of all those techniques using string.
"""
text = "Elementary, My Dear Watson"
# sherlockian quotes
print(text[0])
# print first character
print(text[0:10])
# using range with text (actually it is called slicing) | true |
1ecc10b55b6c37a8018993ec7836cc791fcec003 | rebht78/Python-Exercises | /exercise27.py | 551 | 4.75 | 5 | """
We can access more than one elements using index range.
Suppose a list name is countries.
we can access elements like countries[startindex:endindex]
startindex: starting of index
endindex: till endindex-1
Let's see an example
"""
countries = ['USA','Canada','India','Russia','United Kingdom'];
print(countries[1:3]) # start from index:1 till 2
# will print 'Canada', 'India'
print(countries[1:]) # start from index:1 till the end of the list
# will print Canada','India','Russia','United Kingdom'
# print the whole list
print(countries[:])
| true |
9c8401be726083d2d245e03e6ec55b81d5b708a9 | rebht78/Python-Exercises | /exercise24.py | 594 | 4.59375 | 5 | """
We have learn a lot about python.
Now let's move forward and learn Sequences or Lists.
Lists are collection of values.
Why we need a list in first place?
Let's say you need to store name of all the countries in the world
to store their GDP numbers.
You can go on and create 190+ variables for storing country name
or create a list of countries.
Let's see few examples of it.
Syntax of list creation:
listname = [value1,value2,...]
"""
countries = ['USA','Canada','India','Russia','United Kingdom'];
# we have just created the list
# you can print the list too.
print(countries)
| true |
9c48c238300cf599444b45a59c53749dc8dcfdbd | rebht78/Python-Exercises | /exercise17.py | 520 | 4.21875 | 4 | """
Let's do two more if...else programs to get used to new syntax
of Python.
Problem Statement:
Write a program that display max of two numbers
Sample Input/Output:
3
5
5 is greater than 3
Let's write the program using if...else block
"""
number1 = 3
number2 = 5
if number1 > number2:
# three statements in if...it is valid!
print(number1)
print(' is greater than ')
print(number2)
else:
print(number2)
print(' is greater than ')
print(number1)
# output is not what we expected, but we are getting there... | true |
a745d83b5d9e58ef8b252d9de6485fba11718289 | cmanage1/codewars | /GetMiddleChar.py | 360 | 4.1875 | 4 | #GetMiddleCharacter
#You are going to be given a word. Your job is to return the middle character
#of the word. If the word's length is odd, return the middle character.
#If the word's length is even, return the middle 2 characters.
def get_middle(s):
if len(s) % 2 == 0:
return s[len(s)/2-1] + s[len(s)/2]
else:
return (s[len(s)/2])
| true |
bc5077b9b508b820a70a3dd1f7d1f3796609a297 | Linda-Kirk/cp1404practicals | /prac_09/sort_files_2.py | 1,483 | 4.125 | 4 | import shutil
import os
def main():
"""Create folders from user input and sort files on extension according to user preferences"""
print("Starting directory is: {}".format(os.getcwd()))
# Change to desired directory
os.chdir('FilesToSort')
print("Changed directory is: {}".format(os.getcwd()))
# Create empty dictionary for file extensions and associated category
file_extension_mapped_to_category = {}
for filename in os.listdir('.'):
# Ignore directories, just process files
if os.path.isdir(filename):
continue
file_extension = filename.split('.')[-1]
if file_extension not in file_extension_mapped_to_category:
category = input("What category would you like to sort {} files into? ".format(file_extension))
file_extension_mapped_to_category[file_extension] = category
try:
os.mkdir(category)
print("New folder: ", category)
except FileExistsError:
print("Folder already exists:", category)
pass
print("Moving {} to {}/{}".format(filename, category, filename))
# print("Moving {} to {}/{}".format(filename, file_extension_mapped_to_category[file_extension], filename))
shutil.move(filename, "{}/{}".format(category, filename))
# Print a list of all files in current directory
print("Files in {}:\n{}\n".format(os.getcwd(), os.listdir('.')))
main()
| true |
32015b23ce5e30803fd8f2d086122e87c23bc0ed | Linda-Kirk/cp1404practicals | /prac_02/ascii_table.py | 715 | 4.5625 | 5 | """
This program will generate an ASCII code when a character is inputted by a user
or generate a character when an ASCII code inputted by a user
"""
LOWER = 33
UPPER = 127
character = input("Enter a character: ")
print("The ASCII code for {} is {}".format(character, ord(character)))
ascii_code = int(input("Enter a number between {} and {}: ".format(LOWER, UPPER)))
while not LOWER <= ascii_code <= UPPER:
print("Invalid Number")
ascii_code = int(input("Enter a number between {} and {}: ".format(LOWER, UPPER)))
print("The character for {} is {}".format(ascii_code, chr(ascii_code)))
# ASCII Two Column Table
for value in range(LOWER, UPPER + 1):
print("{:3} {:>3}".format(value, chr(value)))
| true |
46b8e536a1ccafb3dedd1c72dcb5e849c5bf8c8b | Linda-Kirk/cp1404practicals | /prac_01/electricity_bill_estimator.py | 687 | 4.21875 | 4 | """
This program is estimates an electricity bill
"""
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
def main():
print('Electricity bill estimator 2.0')
tariff = input('Which tariff? 11 or 31: ')
while tariff not in ('11', '31'):
print('Invalid tariff!')
tariff = int(input('Which tariff? 11 or 31: '))
if tariff == '11':
tariff = TARIFF_11
else:
tariff = TARIFF_31
daily_use_kwh = float(input('Enter daily use in kWh: '))
number_billing_days = int(input('Enter number of billing days: '))
estimated_bill = daily_use_kwh * number_billing_days * tariff
print('Estimated bill: ${:,.2f}'.format(estimated_bill))
main()
| false |
f0a4498e4c92f8789a813c62c50732adf39b7fc1 | chin33029/python-tutorial | /notes/day_05/dictionary.py | 1,601 | 4.15625 | 4 | # variables
# var = 1
# var = 'string'
# var = 1.0
# var = [0,1,2,3]
# dictionary
# var = {
# "name": "Dean",
# "phone": "123-456-7890"
# }
# dictionary consists of key/value pairs
# {
# key1: value1,
# key2: value2
# }
# person = {
# 'firstName': 'Dean',
# 'lastName': 'Chin',
# 'phone': '123-456-7890'
# }
# print(person['lastName'] + ', ' + person['firstName'])
# liquor = {
# 'name': input('What brand? '),
# 'type': 'Vodka',
# 'price': 100.09
# }
# print(liquor)
# liquor['name'] = input('What brand? ')
# print(liquor)
# liquor['qty'] = int(input('How much? '))
# print(liquor)
# Create a inventory with a max of 10 items
# Each item should have an id (0-9)
# Ask the user if they want to add a liqour or exit
# Eample Flow:
# What do you want to do (add / exit)? add
# What brand? Stoli
# What type? Vodka
# How much is it? 12.34
# What do you want to do (add / exit)? add
# What brand? Titos
# What type? Vodka
# How much is it? 11.44
# What do you want to do (add / exit)? exit
#
# Your inventory is:
# [{'id': 0, 'name': 'Stoli', 'type': 'Vodka', 'price': 12.34}, {'id': 1, 'name': 'Titos', 'type': 'Vodka', 'price': 11.44}]
# What type? Vodka
# How much is it? 12.34
#
# If you add all ten, you should print inventory and say warehouse is full
store = []
store.append({
'name': input('What brand? '),
'type': input('What type? '),
'price': float(input('What price? '))
})
store.append({
'name': input('What brand? '),
'type': input('What type? '),
'price': float(input('What price? '))
})
print(store)
| true |
3d82545a9663de8e2b79d2e5111529cc4ded7605 | chin33029/python-tutorial | /assignments/solutions/assignment_02.py | 1,936 | 4.3125 | 4 | """ Assignment 02 - Bank Example """
def deposit(amount, balance):
""" Deposit money to account """
return int(balance) + int(amount)
def withdraw(amount, balance):
""" Withdraw money from account """
if int(amount) > int(balance):
print(f'Unable to withdraw {amount}, you only have {balance}')
return balance
else:
return int(balance) - int(amount)
if __name__ == "__main__":
# Set the beginning balance
BALANCE = 100
# Welcome the customer
print('\nWelcome to First Python Bank.')
# Tell the user their current balance
print(f'Your current balance is {BALANCE}\n')
# Ask the customer what action do they want to take.
# Uppercase the response too make it easier for comparisons
ACTION = input(
'What would you like to do (Deposit / Withdraw / Exit)? '
).upper()
# Keep processing until the user wants to exit
while ACTION != "EXIT":
# Check if the user entered a valid action
if ACTION in ('DEPOSIT', 'WITHDRAW'):
# Ask the user how much
AMOUNT = input('How much? ')
# Process the transaction
if ACTION.upper() == 'WITHDRAW':
BALANCE = withdraw(AMOUNT, BALANCE)
else:
BALANCE = deposit(AMOUNT, BALANCE)
# Tell the user their new balance
print(f'Your balance is now {BALANCE}\n')
# Tell the user that the entered actionis not valid
else:
print(f'Sorry, {ACTION} is an invalid action.\n')
# Ask the user what they want to do next
ACTION = input(
'What would you like to do (Withdraw / Deposit / Exit)? '
).upper()
# Tell the user what their final balance is
print(f'Your final balance is {BALANCE}.')
# Thank the user for being a customer
print('Thank you for being a First Python Bank customer.')
| true |
28f27700a18f670f6a45bc466ec6cc6de9dce640 | lucas-dcm/exercicios-python | /ex008.py | 672 | 4.15625 | 4 | # Escreva um programa que leia um valor em metros e o exiba convertido em cm e mm.
medida = float(input('Digite sua medida para ser convertida: '))
km = medida / 1000
hm = medida / 100
dam = medida / 10
dm = medida * 10
cm = medida * 100
mm = medida * 1000
print('Sua medida é igual a {}.'.format(medida))
print('Convertido em km é igual a {}.\nConvertido em hm é igual a {}.\nConvertido em dam é igual a {}.\nConvertido em dm é igual {}.\nConvertido em cm é igual {}.\nConvertido em mm é igual {}.'.format(km, hm, dam, dm, cm, mm))
#quilômetro (km) hectômetro (hm) decâmetro (dam) metro (m) decímetro (dm) centímetro (cm) milímetro (ml)
| false |
ea025be2070055c4dede6f77404c8326bb55f567 | AlexKay28/MEPHI_01 | /OOP_Py/polyedr-20191221T113959Z-001/polyedr/common/r3.py | 2,037 | 4.1875 | 4 | from math import sin, cos
class R3:
""" Вектор (точка) в R3 """
# Конструктор
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
# метка на принадлежность точки сфере
# self.bool = True if (x*x+y*y+z*z) > 1 else False
# проверка точки на "хорошесть"
def point_check(self):
# print(round(self.x, 2), round(self.y, 2), round(self.z, 2))
return True if (self.x**2 + self.y**2 + self.z**2) > 1 else False
# Сумма векторов
def __add__(self, other):
return R3(self.x + other.x, self.y + other.y, self.z + other.z)
# Разность векторов
def __sub__(self, other):
return R3(self.x - other.x, self.y - other.y, self.z - other.z)
# Умножение на число
def __mul__(self, k):
return R3(k * self.x, k * self.y, k * self.z)
# Поворот вокруг оси Oz
def rz(self, fi):
return R3(
cos(fi) * self.x - sin(fi) * self.y,
sin(fi) * self.x + cos(fi) * self.y, self.z)
# Поворот вокруг оси Oy
def ry(self, fi):
return R3(cos(fi) * self.x + sin(fi) * self.z,
self.y, -sin(fi) * self.x + cos(fi) * self.z)
# Скалярное произведение
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
# Векторное произведение
def cross(self, other):
return R3(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
if __name__ == "__main__":
x = R3(1.0, 1.0, 1.0)
print("x", type(x), x.__dict__)
y = x + R3(1.0, -1.0, 0.0)
print("y", type(y), y.__dict__)
y = y.rz(1.0)
print("y", type(y), y.__dict__)
u = x.dot(y)
print("u", type(u), u)
v = x.cross(y)
print("v", type(v), v.__dict__)
| false |
2fb88d34c58a9d27256856585c7230371f23aeda | ppradnya18/first-Basic | /caleder_module.py | 301 | 4.15625 | 4 | """12. Write a Python program to print the calendar of a given month and year."""
import calendar
import inspect
print(calendar.Calendar)
print(inspect.getfile(calendar))
print(dir(calendar))
y = int(input("Input the year : "))
m = int(input("Input the month : "))
print(calendar.month(y, m))
| true |
2a6f89f77b2016a6e1cade21760bae88dcfe40aa | alan199912/Pyhton | /Ejercicios 1/00-funcionMax.py | 541 | 4.1875 | 4 | # Definir una función max() que tome como argumento dos números y devuelva el mayor de ellos.
# (Es cierto que python tiene una función max() incorporada, pero hacerla nosotros mismos es un muy buen ejercicio.
def maximo(num1, num2):
if num1 > num2:
return print("El numero ", num1 , "es mas grande que ", num2)
else:
return print("El numero ", num2 , "es mas grande que ", num1)
numero1 = int(input("ingrese un numero "))
numero2 = int(input("ingrese un segundo numero "))
maximo(numero1,numero2) | false |
11e2a969f22e542a611090dd3271d386ba17476b | welydharmaputra/ITP-lab | /New triangle.py | 2,482 | 4.1875 | 4 | def main():
for x in range(1,6): # it will make the stars go down
for z in range(1,int(x)+1,1): # it will make the star increase one by one
print("*",end="") #it will print the stars and make the stars to make a line that from left to the right
print() # it make the stars can be show
if __name__=="__main__":
main()
print("\n")
def main():
for x in range(1,6): # it will make the stars go down
for y in range(1,6-int(x)): # it will make the space
print(" ",end="")
for z in range(1,int(x)+1,1): #it will make the stars and increase the stars one by one
print("*",end="")
print()
if __name__=="__main__":
main()
print("\n")
def main():
for x in range(1,7): # it will make the stars go down
for z in range(1,7-int(x),1): # it will make the stars and decrease the stars one by one
print("*",end="")
print()
if __name__=="__main__":
main()
print("\n")
def main():
for x in range(1,7): # it will make the stars go down
for y in range(1,int(x)+1):# it will make the space
print(" ",end="")
for z in range(1,7-int(x),1): # it will make the stars that from 7 stars go to 1 on star
print("*",end="")
print()
if __name__=="__main__":
main()
print("\n")
def main():
for x in range (1,6): # it will make the stars go down
for y in range (1,6-x): #it will make the spaces
print(" ",end="")
for z in range(2, int(x)*2+1): # it will make make the stars and increase the stars two by one
print("*", end="")
print()
if __name__=="__main__":
main()
print("\n")
def main():
for x in range (1,6): # it will make the stars go down
for y in range (1,6-x):
print(" ",end="")
for z in range(2, int(x)*2+1):
print("*", end="")
print()
for d in range (1,6): # it will make the stars go down
for k in range(1,int(d)+1): #it will make the left-below side or te diamond with space
print(" ",end="")
for k in range(2,6-int(d),1): #it will print the lefe-below stars of diamond
print("*",end="")
for m in range(1,6-int(d),1): #it will print the right-below stars of diamond
print("*",end="")
print()
if __name__=="__main__":
main()
| true |
137dc3aa161daf4a4e6d0f4e666cd232c4dd0225 | sureshyhap/Python-Crash-Course | /Chapter 7/6/three_exits.py | 509 | 4.1875 | 4 | topping = ""
while topping != "quit":
topping = input("Enter a topping: ")
if topping != "quit":
print("I will add " + topping + " to the pizza")
active = True
while active:
topping = input("Enter a topping: ")
if topping == "quit":
active = False
else:
print("I will add " + topping + " to the pizza")
while True:
topping = input("Enter a topping: ")
if topping == "quit":
break
else:
print("I will add " + topping + " to the pizza")
| true |
f09e36813c4fc46424781e2d98255410d81ca8dc | sureshyhap/Python-Crash-Course | /Chapter 4/13/buffet.py | 249 | 4.21875 | 4 | foods = ('burgers', 'fries', 'lasagna', 'alfredo', 'macaroni')
for food in foods:
print(food)
new_food1 = 'chicken'
new_food2 = 'vegan burger'
foods = (new_food1, new_food2, foods[2], foods[3], foods[-1])
for food in foods:
print(food)
| true |
9203ba6034915302abb40d4cca075868a75deaa2 | MrDarnzel/Total-Price | /Celsius.py | 385 | 4.375 | 4 | Temp_Celsius = input(" What is the Temperature in Celsius? ") #Asks the user for Temperature in Celsius
float(Temp_Celsius) #Converts to Float
print(Temp_Celsius) #Prints Celcius Temperature
Temp_Fahrenheit = (((float(Temp_Celsius) * 9) / 5) + 32) #Takes C and converts into F
print(" The temperature in Fahrenheit is " + str(Temp_Fahrenheit)) #Prints your temperature
| true |
6e66b40d00311001955228f68f137409e42635f0 | LilyLin16/learning-python3 | /samples/basic/function.py | 2,187 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python 函数的参数传递:
# 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。
# 比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。
# 可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响。
def changeInt(a):
a = 10
print(a)
# 实例中有 int 对象 2,指向它的变量是 b,在传递给 ChangeInt 函数时,
# 按传值的方式复制了变量 b,a 和 b 都指向了同一个 Int 对象,在 a=10 时,
# 则新生成一个 int 值对象 10,并让 a 指向它。
b = 2
changeInt(b)
print(b) # 结果是 2
def changeme(mylist):
# "修改传入的列表"
mylist.append([1, 2, 3, 4])
print("函数内取值: ", mylist)
return
# 调用changeme函数
mylist = [10, 20, 30]
print("初始值: ", mylist)
changeme(mylist)
print("函数外取值: ", mylist)
# 可写函数说明
def printinfo(name, age):
print("名字: ", name)
print("年龄: ", age)
return
printinfo(age=50, name="runoob")
# 不定长参数: 加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。
# 加了两个星号 ** 的参数会以字典的形式导入。
def printinfo(arg1, *vartuple):
print("输出: ")
print(arg1)
print(vartuple) # (60,50)
for var in vartuple:
print(var)
return
printinfo(10)
printinfo(70, 60, 50)
total = 0 # 这是一个全局变量
# 可写函数说明
def sum(arg1, arg2):
""""返回2个参数的和.""" # 函数的说明文档
total = arg1 + arg2 # total在这里是局部变量.
print("函数内是局部变量 : ", total) # 30
return total
# 调用sum函数
sum(10, 20)
print(sum.__doc__)
print("函数外是全局变量 : ", total) # 0
num = 1
def fun1():
global num # 需要使用 global 关键字声明
print(num) # 1
num = 123
print(num) # 123
fun1()
print(num) # 123
| false |
54d2037bb436d0bc5b6d4eff3c52dbac36683fc3 | HamMike/extra_python_exercises | /single_one.py | 421 | 4.1875 | 4 | # Given an array of integers, every element appears twice except for one.
# Implement a program that will print that single one.
# Example: [1,1,2,2,3,3,4,5,5,6,6,7,7] - 4 would be the odd man out
# Note:
# Your algorithm should have a linear runtime complexity.
# *** your code here ***
#Steve's solution
def find_odd(a):
return [x for x in a if a.count(x) < 2][0]
print(find_odd([1,1,2,2,3,3,4,5,5,6,6,7,7]))
| true |
1188c4eefe1d9093d1d428b08c0531d801541f90 | Raspberriduino/PythonBeginnerProjects | /FAQ Questions Program - Dictionary Data Structure Practice/FAQ Data Entry Program.py | 2,449 | 4.21875 | 4 | #
#
# David Pierre-Louis
# August 11, 2019
# SEC 290 32784.201930 SUMMER 2019 - Block II
# Programming Assignment 5
#
# Create a Python program that will serve as a
# menu-driven interface that manages a dictionary
# of Frequently Asked Questions (FAQ's)
#
# Questions serve as the keys and answers serve as
# the values.
#
#
#
menu = """
==========================
Frequently Asked Questions
==========================
0: Exit
1: List FAQ's
2: Add FAQ
3: Delete FAQ
"""
faq_dictionary = {}
done = False
while not done:
print(menu)
selection = input("Please enter a choice: ")
print () #Blank line for spacing
if selection == "0":
done = True
elif selection == "1":
for question, answer in faq_dictionary.items():
print("Question: {} \nAnswer: {:>6} \n".format(question, answer))
elif selection == "2":
while True:
question = input("Please enter the question: ")
if question in faq_dictionary:
print("\n{} is already in the notebook. \nPlease rephrase the question.".format(question))
print()
continue
else:
answer = input("Please enter the answer: ")
faq_dictionary[question] = answer
print("\nYour question has been added to the notebook.")
break
elif selection == "3":
while True:
del_question = input("Please enter the question to be deleted: ")
if del_question in faq_dictionary:
del(faq_dictionary[del_question])
print("\n{} has been removed from the FAQs".format(del_question))
print()
break
else:
print("\nCould not find {} in the FAQs. \nNo changes made. \n".format(del_question))
break
else:
print("Warning! {} is not a valid entry.".format(selection))
print()
leave = input("Would you like to Try Again? [y/n]") # Asking the user if they wanted to continue running the program
leave = leave.upper()
if leave == "Y":
continue
if leave == "YES":
continue
else:
break
print("Thank you for using the Frequently Asked Questions! Your session is now Done!")
| true |
423b4396d2a14034c9e5120127c7a88e396d10ea | rohinikuzhiyampunathumar/Python | /arrays.py | 1,104 | 4.15625 | 4 | from array import *
# import array as arr
# use this if you are using import array as arr
# vals = arr.array('i',[4,-3,7,3])
# print(vals)
# vals.reverse()
# print(vals)
vals = array('i',[7,8,4,-3,6,8])
print(vals)
for i in range(6):
print(vals[i])
for i in range(len(vals)):
print(vals[i])
for i in vals:
print(i)
# assigning values to a new array from the old array
newArr = array(vals.typecode, (a for a in vals))
# if you know the type of the other array then you can use the below
newArr1 = array('i',(a for a in vals))
print(newArr1)
# while loop
i=0
while i < len(newArr):
print(newArr[i])
i+=1
# Array values fron user input
ipArr = array('i',[])
size = int(input("Enter the length of the array"))
for i in range(size):
value = int(input("Enter the value :"))
ipArr.append(value)
print(ipArr)
# To search a value in the array and to print the index of that element
srch = int(input("Enter the search value"))
k = 0
for e in ipArr:
if(e==srch):
print(k)
k+=1
#another direct way
print(ipArr.index(srch)) | true |
9071e4cf7cb405a6105ba56342505a37232eae88 | KamranHussain05/CS3A-OOP-Python | /kamranHussainLab2.py | 2,033 | 4.125 | 4 | ###########################################################
# Name: Kamran Hussain
# Date: 7/13/2021
# Course: CS 3A Object-Oriented Programming Methodologies in Python
# Lab 2: Programming with Numbers and Strings; Controlling Selection
# Description: A console based program that calculates the value of a coupon
# based on the amount of a grocery bill.
# ###########################################################
# Source code:
def main(): # alternative function name is groceryCouponCalculator
n = float(input('Please enter the cost of your groceries: $'))
while n<0:
n = float(input('The value you entered is negative, please enter a ' +
'positive value: '))
if n < 10.0:
print('You win a discount coupon of $0.00 (0% of your purchase)')
elif 10 <= n < 60:
percentage = 0.08
discount = n*percentage
formatted_value = "{:.2f}".format(discount)
print('You win a discount coupon of $' + str(formatted_value) +
' (8% of your purchase)')
elif 60 <= n < 150:
percentage = 0.10
discount = n*percentage
formatted_value = "{:.2f}".format(discount)
print('You win a discount coupon of $' + str(formatted_value) +
' (10% of your purchase)')
elif 150 <= n < 210:
percentage = 0.12
discount = n*percentage
formatted_value = "{:.2f}".format(discount)
print('You win a discount coupon of $' + str(formatted_value) +
' (12% of your purchase)')
elif n >= 210:
percentage = 0.14
discount = n*percentage
formatted_value = "{:.2f}".format(discount)
print('You win a discount coupon of $' + str(formatted_value) +
' (14% of your purchase)')
# program entry point
if __name__=='__main__':
main()
# Sample Run:
'''
Please enter the cost of your groceries: $-160
The value you entered is negative, please enter a positive value: 160
You win a discount coupon of $19.20 (12% of your purchase)
'''
| true |
9dba312c2409873e6c12195400b76fc4e0e2613f | sidlokam/Python-Addition | /Addition.py | 251 | 4.15625 | 4 | def addition(number1, number2) :
return number1 + number2
number1 = int(input("Enter First Number : "))
number2 = int(input("Enter Second Number : "))
number3 = addition(number1, number2)
print("the sum of the two numbers is : "+ str(number3))
| true |
08f04d54ded1d3193a5b51b4a86e0604ed486385 | hacker95-bot/SE-HW1 | /code/__init__.py | 267 | 4.25 | 4 | x = 10
def factorial(n):
"""
Recursive Function to calculate the factorial of a number
:param n: integer
:return: factorial
"""
if n <= 1:
return 1
return n * factorial(n - 1)
if __name__ == "__main__":
print(factorial(x))
| true |
29b502c6ed653436532576ea3cd4c46413493009 | A01375137/Tarea-06 | /tarea6.py | 2,232 | 4.125 | 4 | # Autor: Mónica Monserrat Palacios Rodríguez
# UTF-8
# Tarea 6
#Función que calula los insectos
def recolectarInsectos():
insectos = 0
dias = 0
print("Bienvenido al programa que registra los insectos que recolectas")#Se da la bienvenida
while insectos < 30: #Se abre ciclo while para que se repita hasta que se indique lo contrario
numInsectos = int(input("¿Cuántos insectos atrapaste hoy? "))
dias = dias+1
insectos = insectos + numInsectos
insectosFaltantes = 30 - insectos
insectosSobrantes = insectos - 30
print ("Después de %d día(s) de recolección, llevas %d insectos" %(dias, insectos))
if insectos < 30: #Ifs para dar los comentarios adecuados o indicar que ganó
print ("Te hace falta recolectar %d insectos" %insectosFaltantes)
else:
print("Te has pasado con %d insectos" % insectosSobrantes)
print("¡Felicidades, has llegado a la meta!")#Si sale de while es que ha llegado a la meta
print(" ")
#Función para encontrar el mayor
def encontrarElMayor():
print("Bienvenido al programa que encuentra al mayor")#Bienvendia al programa
numeros = []#Se crea la lista
num = int(input("Teclea un múmero [-1 para salir] "))
if num == -1:
print("No hay valor mayor")
elif num < -1:
print("Sólo números enteros positivos por favor")
else:
while num != -1:
numeros.append(num)
num = int(input("Teclea un múmero [-1 para salir] "))
print ("El mayor es: ", max(numeros))
print(" ")
#Función principal
def main():
#Letreros de bienvenida y explicación
print ("Tarea 06. Ciclos While")
print ("Autor: Mónica Monserrat Palacios Rodríguez")
print(" ")
print ("1. Recolectar insectos")
print ("2. Encontrar el mayor")
print ("3. Salir")
opcion = int(input("Teclea tu opción: "))
print(" ")
while 1:#Comienza el while del menú
if opcion == 1:
recolectarInsectos()
elif opcion == 2:
encontrarElMayor()
elif opcion == 3:
print("Gracias por usar este programa, regresa pronto")
break
else:
print("ERROR, teclea 1, 2 ó 3")
break
main() | false |
e3ef5a553583b8f9612d1672d0e74e5b6edd7345 | MengleJhon/python_1 | /parrot.py | 527 | 4.25 | 4 | message = input("Tell me something, and I will repeat it back to you: ")
print(message)
name = input("Please enter your name: ")
print("Hello, " + name + "!")
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
age = input("How old are you? ")
print(age)
print(int(age))
# print(age >= 18) # 错误
print(int(age) >= 18)
# print("His age is " + int(age) + ".") # 错误
print("His age is " + age + ".") | true |
e039a0b6781bbdae332d45fd561ad66b28fdf284 | sharkfinn23/Birthday-quiz | /birthday.py | 2,500 | 4.6875 | 5 | """
birthday.py
Author: Finn
Credit: none
Assignment:
Your program will ask the user the following questions, in this order:
1. Their name.
2. The name of the month they were born in (e.g. "September").
3. The year they were born in (e.g. "1962").
4. The day they were born on (e.g. "11").
If the user's birthday fell on October 31, then respond with:
You were born on Halloween!
If the user's birthday fell on today's date, then respond with:
Happy birthday!
Otherwise respond with a statement like this:
Peter, you are a winter baby of the nineties.
Example Session
Hello, what is your name? Eric
Hi Eric, what was the name of the month you were born in? September
And what year were you born in, Eric? 1972
And the day? 11
Eric, you are a fall baby of the stone age.
"""
from datetime import datetime
from calendar import month_name
todaymonth = datetime.today().month
todaydate = datetime.today().day
todaymonth = month_name[todaymonth]
name = input("Hello, what is your name? ")
month = str(input("Hi {0}, what was the name of the month you were born in? " .format(name)))
year = int(input("And what year were you born in, {0}? " .format(name)))
day = int(input("And the day? "))
if month == "October":
halloweenmonth = 1
else:
halloweenmonth = 0
if day == 31:
halloweenday = 1
else:
halloweenday = 0
if halloweenday == 1 and halloweenmonth == 1:
halloween = 1
else:
halloween = 0
if todaymonth == month:
birthmonth = 1
else:
birthmonth = 0
if todaydate == day:
birthday = 1
else:
birthday = 0
if birthday == 1 and birthmonth == 1:
birthdate = 1
else:
birthdate = 0
if month == "June" or month == "July" or month == "August":
season = "summer"
elif month == "March" or month == "April" or month == "May":
season = "spring"
elif month == "September" or month == "October" or month == "November":
season = "fall"
elif month == "December" or month == "January" or month == "February":
season = "winter"
else:
season = "none"
if year >= 2000:
yeard = "two thousands"
elif year <= 1980:
yeard = "stone age"
elif year < 2000 and year >= 1990:
yeard = "nineties"
elif year < 1990 and year >= 1980:
yeard = "eighties"
else:
yeard = "you gave me an invalid year"
if halloween == 1:
print("You were born on Halloween!")
else:
if birthdate == 1:
print("Happy birthday!")
else:
print("{0}, you are a {1} baby of the {2}." .format(name, season, yeard))
| true |
314ea8b713dba09f9499c694b9200671736ec0a8 | meikesara/Heuristieken | /algorithms/simulatedannealing.py | 2,784 | 4.25 | 4 | """
Script to run a simulated annealing algorithm with a logarithmic cooling
rate (temperature = D/ln(iteration + 2) - D/ln(10^6)). From the 10^6-2th
iteration the temperature will be D/ln(10^6 - 1) - D/ln(10^6).
Meike Kortleve, Nicole Jansen
"""
import copy
import math
import random
import matplotlib.pyplot as plt
from classes.amino import Amino
from classes.protein import Protein
import helper.visualizer as visualizer
def simulatedAnnealing(protein, D, iterations, runnings=False):
"""
Run simulated annealing.
Returns the protein the with best stability and also the stability if only
one running is performed.
Arguments:
proteinString -- a string that contains the amino acids of the protein
D -- positive integer, determines the cooling rate
iterations -- positive integer, the amount of iterations of the algorithm
runnings -- boolean, True if multiple runnings of the algorithm are run,
False if algorithm is run once (default)
"""
stabilityList = []
tempList = []
translation = pow(10, 6)
bestProtein = protein
for k in range(iterations):
stabilityList.append(protein.stability)
# Create a new protein by moving the amino acids
newProtein = protein.pullMove()
# Update the temperature
if k < (translation - 2):
temperature = D/math.log(k + 2) - D/math.log(translation)
else:
temperature = D/math.log(translation -1) - D/math.log(translation)
tempList.append(temperature)
# Set acceptance to 1 if the stability of the new protein is better.
if newProtein.stability < protein.stability:
acceptance = 1
else:
acceptance = math.exp((protein.stability - newProtein.stability)
/ temperature)
# Accept newProtein if the acceptance exceeds random number from 0 to 1.
if (acceptance > random.random()):
protein = newProtein
# If the stability of newProtein is the best set as bestProtein
if newProtein.stability < bestProtein.stability:
bestProtein = newProtein
if runnings:
return bestProtein
else:
# Add final stability to stabilityList
stabilityList.append(protein.stability)
print("Final solution stability: ", protein.stability)
print("Best stability: ", bestProtein.stability)
visualizer.plotProtein(bestProtein)
visualizer.plotStability(stabilityList)
# Plot temperature change
plt.plot(tempList)
plt.title("Temperature")
# Plot acceptance change
plt.figure()
plt.plot([math.exp(-1/elem) for elem in tempList])
plt.title("acceptance")
plt.show()
| true |
d61ab7bdd40531e7cc20ce49e796e631dda31588 | interpegasus/book | /python/data_structures/linked_list.py | 2,511 | 4.15625 | 4 | class Node:
def __init__(self, data, next):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
def is_empty(self):
return self.length == 0
def insert(self, data):
new_node = Node(data,None)
if self.head is None:
self.head = new_node
else:
current_node = self.head
while(current_node.next is not None):
current_node = current_node.next
current_node.next = new_node
print ("New node has been added: {}".format(new_node.data))
self.length += 1
return new_node
def traversal(self):
current_node = self.head
index = 0
while(current_node is not None):
index += 1
print("Item {}: {} \n".format(index,current_node.data))
current_node = current_node.next
def search(self, data):
current_node = self.head
while(current_node is not None):
if current_node.data == data:
return True
current_node = current_node.next
return False
class TestLinkedList:
def __init__(self):
# call tests
self.test_is_empty()
self.test_insert()
self.test_search()
def test_is_empty(self):
new_list = LinkedList()
assert new_list.is_empty() == True, new_list
new_list.insert(1)
assert new_list.is_empty() == False, new_list
print('Test list is empty: succesfull.')
def test_insert(self):
new_list = LinkedList()
items = [1,2,3,4,5,6,7]
for data in items:
new_list.insert(data)
assert len(items) == new_list.length
assert new_list.length == 7
new_list.traversal()
print('Test insert in list: succesfull.')
def test_search(self):
new_list = LinkedList()
items = [1,2,3,4,5,6,7]
for data in items:
new_list.insert(data)
assert new_list.search(3) == True
assert new_list.search(31) == False
print('Test search in list: succesfull.')
TestLinkedList()
# new_list = LinkedList()
# print(new_list.is_empty())
# new_list = LinkedList()
# items = [1,2,3,4,5,6,7]
# for data in items:
# new_list.insert(data)
# print(new_list.is_empty())
# new_list.traversal()
# new_list.search(5) | true |
942afab63fcbdd0514ac581a6d4fa3ed9790e2ea | sabrupu/comp151 | /Lab9/Problem2.py | 631 | 4.15625 | 4 | # Write a function that will accept a list of numbers and calculate the median.
# Input: [20, 10, 5, 15]
# Output: The median is 12.5.
# Input: [20, 10, 5, 15, 30]
# Output: The median is 15
def median(list):
sort_list = sorted(list)
length = len(list)
middle = length // 2
if length == 1:
return sort_list
elif length % 2 == 0:
return sum(sort_list[middle - 1 : middle + 1]) / 2
else:
return sort_list[middle]
def main():
list = [20, 10, 5, 15]
print(f'The median is {median(list)}.')
list = [20, 10, 5, 15, 30]
print(f'The median is {median(list)}.')
main()
| true |
65f0cf1442e5485adebc89db4e9b5b6fb636309d | sabrupu/comp151 | /Lab6/Problem1.py | 729 | 4.34375 | 4 | # Write a function that will accept two arguments, a string and a character. Your function
# should search the string for and count the number of occurrences of the given character.
#
# Enter the string to search: Sally sells sea shells down by the sea shore.
# Enter the character to count: s
#
# There were 8 s's in that string.
def search_string(string, char):
count = 0
for c in string:
if c.lower() == char.lower():
count += 1
return count
def main():
string = input('Enter a string to search: ' )
character = input('Enter the character to count: ')
count = search_string(string, character)
print(f'There were {count} {character}\'s in that string.')
main()
| true |
ee571416c44ff8cc7a299db5a141341ef26f5417 | sabrupu/comp151 | /Lab6/Problem2.py | 451 | 4.28125 | 4 | # Write a function that will convert a list of characters into a string. Return this string to
# main and display it.
# # Input: [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
# # Output: “Hello”
def join_chars(char_list):
str = ''
for c in char_list:
str += c
return str
def main():
input = ['H', 'e', 'l', 'l', 'o', ' ', 'p', 'r', 'o', 'f.']
output = join_chars(input)
print(input)
print(output)
main()
| true |
f525d1dfb123d4faac7482d9c8fe9453a35bd153 | sabrupu/comp151 | /PAL/Assignment2/Problem1.py | 255 | 4.21875 | 4 | # Write a program that will read a number n from the user then print all values from 1-n.
# Example:
# Enter a number: 6
# 1 2 3 4 5 6
def main():
n = int(input('Enter a number: '))
for i in range(1, n + 1):
print(i, end=' ')
main()
| true |
c6f618ed9dc14d50a766a6e6d6138a6e92bdb6dc | sabrupu/comp151 | /PAL/Assignment2/Problem2.py | 478 | 4.3125 | 4 | # Write a program that will read a number n from the user then print and sum all even
# numbers from 1-n.
# Enter a number: 12
# 2 + 4 + 6 + 8 + 10 + 12 = 42
def main():
# Enter user input
n = int(input('Enter a number: '))
# Loop through even natural numbers up to n
sum = 0
str = ''
for i in range(2, n+1, 2):
sum += i
str += f'{i} + '
# Complete and print output string
str = str[:-3] + f' = {sum}'
print(str)
main()
| true |
9b4ee102cee05b58e23b92afbb55d41475b21b2c | dubeyji10/Learning-Python | /Day6/.idea/iterator1.py | 1,067 | 4.71875 | 5 | #iterator
# ---- it is an object that represents a stream of a data
# it returns the stream or the actual data in the stream (one element at a time)
#an object that supports iteration is called itertion
# two iterable objects we've seen already so far --- strings and lists
string = "1234567890"
# for char in string:
# print(char,end=" ")
#for terminates when error? generates
# ( error here is something when end of iterable object occurs
# it is not visible but that's what terminates the loop)
# for vs iter()
my_iterator = iter(string)
print(my_iterator)
#the iterable object
#iterating one element at a time
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
# now if we add it will give error because there weren't any element
print(next(my_iterator))
for char in string:
print(char)
print("\n\n\n")
for char in iter(string):
print(char) | true |
37379bb285ea9c80f8512cc9f64a2e7db4ff7ebc | dubeyji10/Learning-Python | /Day5/.idea/lists2.py | 1,095 | 4.28125 | 4 | list1 = []
list2 = list() #constructor ?
print(" List 1 : {}".format(list1))
print(" List 2 : {}".format(list2))
if list1 == list2 :
print(" lists are equal")
#passsing a string to the list
#creates a list with each character
print(list(" the lists are equal ")) # see the output
print(" \n------ reversing a list ------\n")
even = [2,4,6,8]
even2 = even
even2.sort(reverse=True)
print("\noriginal list of even is also sorted : ",even,"\n--")
print(even2)
print("even variable was also updated \n"
"--------------------\n--------------------\n"
"--------------------")
another_even = even
print(another_even is even) #this returns true
another_even.sort(reverse=True)
print(even)
# another_even2 = list(even) # a constructor and
# # passing list even to it which returns a new list
# print( "\n !!!! see source !!!!")
# print(another_even2 is even) # this returns false
# another_even2.sort(reverse=True)
# #make the required --- excep for declaration of even
# # above code comment and see
# print(even) # false -- line 33 so
# # ' even ' list (original) is not reversed | true |
105553aaa9066d677220be514c9c396c389450e5 | dubeyji10/Learning-Python | /Day9(Dictionaries and Sets)/.idea/DS14.py | 708 | 4.1875 | 4 | #more on sets
even_set = set(range(0,40,2))
print(even_set) #* unordered
print(len(even_set))
print("--"*30)
squares_tupple = (4,6,9,16,25)
squares = set(squares_tupple)
print(squares)
print(len(squares))
print("--"*30)
#union of sets
#mathematical union ------- one item on time
print(even_set.union(squares))
#intersection of sets
print("--"*30)
print(even_set.intersection(squares))
print("--"*30)
#since sets are unordered ------ sorting -------
print(sorted(even_set))
print("--"*30)
print(" even minus square : ",even_set.difference(squares))
print(sorted(even_set - squares)) # also works// '-' sign
print("--"*30)
print("sqaures minus even :",squares.difference(even_set))
print(squares-even_set) | true |
6face84af864ea99dd3865d56d51719bba6a41bb | dubeyji10/Learning-Python | /Day9(Dictionaries and Sets)/.idea/DS1.py | 1,046 | 4.46875 | 4 | #Dictionaries
#are unordered
#contain key valued pairs
#values are not accessed by an index but by means of a key
fruit = {"orange": "a sweet, orange, citrus fruit",
"apple": "good for making cider",
"lemon": "a sour,yellow citrus fruit",
"grape": "a small, sweet fruit growing in bunhces",
"lime": "a sour,green citrus fruit"
}
print(fruit)
print("-"*20)
print("lemon --------",fruit["lemon"]) # using key which is seperated by a colon
print("-"*40)
# new key
fruit["pear"] = "an odd shaped apple"
print(fruit) #pear is added to the dictionary
print("-"*40)
fruit["lime"] = " great with tequila"
print(fruit) #lime is updated -----------------------
print("-"*40,"\n lemon is deleted from dictionary ")
del fruit["lemon"]
print(fruit)
# print("-"*40,"\n deleting the whole dictionary")
# del fruit
# print(fruit) # gives error
print("-"*40)
# fruit.clear() #contents of fruit deleted
# print(fruit)
#
print(fruit["tomato"]) #key error since tomato is not in the dictionary
print("-"*40)
| true |
965c6d04d1bd7d9d483c3a4bf1caa848ec992230 | dubeyji10/Learning-Python | /PythonDay2/.idea/Day2a.py | 1,060 | 4.28125 | 4 | #undo next 3 lines
# greeting="HELLO"
# name=input("Enter you name ")
# print(greeting+' '+name)
#backslash gives a special meaning
#splitString
#and tabString show
# to put something in a comment select that part and use ctrl+/ button to make it a
# comment and undo it
splitString = " This string has been \nsplit over \nseveral\ntimes\nas\nyou can \nsee"
print(splitString)
tabString = " t1 \t t2\tt3\t\kt12312\t3\t\t213123213"
print(tabString)
print(' the pet shop owner said "NO NO ,no \'e \'s uhh........ he\s resting" ')
#see difference in use of quotes single and double
print(" the pet shop owner said \"No No , no , 'e 's uhh.... he's resting\"")
anotherSplitString = """The string has been
split over
several line .. using triple quotes"""
print(anotherSplitString)
print(''' the pet shop owner said " NO , no , 'e 's uh .. , he's resting " ''')
#now take care with 4 double quotes remove space ......here b/w quotes one and triple
print("""the pet shop owner said "no , no , 'e 's uh.... , he's resting" """)
# and it will give error | true |
4fb1d0b6cc215c9f69388938f51e66d0e795c954 | dubeyji10/Learning-Python | /Day5/.idea/lists3.py | 390 | 4.3125 | 4 | even = [2,4,6,8]
another_even2 = list(even) # a constructor and
# passing list even to it which returns a new list
print( "\n !!!! see source !!!!")
print(another_even2 is even) # this returns false
another_even2.sort(reverse=True)
#make the required --- excep for declaration of even
# above code comment and see
print(even) # false -- line 33 so
# ' even ' list (original) is not reversed | true |
acf9882273eff9d2bdc46832f594cb58fc281a64 | hr21don/Single-Linked-List | /main.py | 883 | 4.21875 | 4 | # A single node of a singly linked list
class Node:
# constructor
def __init__(self, data):
self.data = data
self.next = None
# A Linked List class with a single head node
class LinkedList:
def __init__(self):
self.head = None
# insertion method for the linked list
def insert(self, data):
new_node = Node(data)
if(self.head):
current = self.head
while(current.next):
current = current.next
current.next = new_node
else:
self.head = new_node
# print method for the linked list
def print_List(self):
current = self.head
while(current):
print(current.data)
current = current.next
# Singly Linked List with insertion and print methods
L_List = LinkedList()
L_List.insert(23)
L_List.insert(43)
L_List.insert(83)
L_List.insert(83)
L_List.insert(83)
L_List.insert(100)
L_List.print_List() | true |
75f5e69447c91b87a4bed209d3a1af851b30973e | rtanvr/pathon | /text/palindrome.py | 280 | 4.15625 | 4 | #See if string is a palindrome
class StringMan():
def palindrome(self, string):
if string == string[::-1]:
return "Palindrome"
else:
return "Not Palindrome"
if __name__ == '__main__':
x = StringMan()
string = input("Enter a string: ")
print (x.palindrome(string))
| true |
5b439a568e1470c2f31dfa8acb586b700d213b18 | Yanasla/SF | /functions/Args.py | 751 | 4.34375 | 4 |
#Теперь немного практики для закрепления. Определите функцию sum_args, которая суммирует все свои аргументы.
# Например, sum_args(10, 15, -4) должна возвращать 21
def sum_args(*args):
summ = 0
for element in args:
summ += element #summ = summ + element
return summ
print(sum_args(10, 15, -4))
#Переменное число аргументов
def multiply(*args):
product = 1
for num in args:
product *= num #product = product * num
return product
print(multiply(2))
# => 2
print(multiply(8, 3, 4))
# => 96
print(multiply(1, 2, 3, 4, 5, 6))
# => 720
| false |
abdd50f5adcd3532c2ec2656b9810c254c7f577d | Yanasla/SF | /itog.py | 281 | 4.125 | 4 | string = "TURBO"
reversed_string = string[::-1]
print(reversed_string)
print('apples'.upper() in 'I like APPLES'.upper())
print('your' in 'WhAt Is YoUr NaMe?'.lower())
X ='55,66'
print(float(X.replace(',', '.')))
#print(int(X.replace(',', '.')))
print(float(X.replace(',', '.'))) | false |
704e6e4af0e148a6f7a21ee0312ed513a68d6383 | AdrianaChavez/rockpaperscissors | /rps.py | 1,176 | 4.125 | 4 |
list = ["rock","paper","scissors"]
import random
computer_choice = (random.choice(list))
user_input = input("Let's play Rock Paper Scissors. Which do you choose? (Type 'Rock', 'Paper', or 'Scissors'")
print("Rock, paper, scissors, shoot!")
if user_input=="Rock" and computer_choice=="rock":
print("I chose rock too. We tied.")
elif user_input=="Rock" and computer_choice=="paper":
print("I chose paper. I win.")
elif user_input=="Rock" and computer_choice=="scissors":
print("I chose scissors. You win.")
elif user_input=="Paper" and computer_choice=="rock":
print("I chose rock. You win.")
elif user_input=="Paper" and computer_choice=="paper":
print("I chose paper too. We tied.")
elif user_input=="Paper" and computer_choice=="scissors":
print("I chose scissors. I win.")
elif user_input=="Scissors" and computer_choice=="rock":
print("I chose rock. I win.")
elif user_input=="Scissors" and computer_choice=="paper":
print("I chose paper. You win.")
elif user_input=="Scissors" and computer_choice=="scissors":
print("I chose scissors too. We tied.")
else:
print("There's been an error. Please make sure your response is valid.")
| true |
5e4ca3203ffa1b4742e5206b71c68ab4142eb74b | michalkasiarz/learn-python-programming-masterclass | /program-flow-control-in-python/ForLoopsExtractingValuesFromInput.py | 432 | 4.28125 | 4 | # For loops extracting values from user input
# prints entered number without any separators
number = input('Please enter a series of numbers, using any separators you like: ')
separators = ''
numberWithNoSeparators = ''
for char in number:
if not char.isnumeric():
separators = separators + char
else:
numberWithNoSeparators = numberWithNoSeparators + char
print(separators)
print(numberWithNoSeparators) | true |
95edfc4291b87aaf46304869b4d4b724365e01d3 | michalkasiarz/learn-python-programming-masterclass | /lists-ranges-and-tuples-in-python/ListsIntro.py | 856 | 4.34375 | 4 | # Introduction to lists
# ip_address = input("Please enter an IP address: ")
# print(ip_address.count("."))
parrot_list = ["non pinin", "no more", "a stiff", "bereft of live"]
parrot_list.append("A Norwegian Blue")
for state in parrot_list:
print("This parrot is " + state)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = even + odd
sorted_numbers = sorted(numbers) # sorted() is a built-in function
print(f"Numbers: {numbers}")
print(f"Sorted_numbers {sorted_numbers}")
if numbers == sorted_numbers:
print("The lists are equal")
else:
print("The lists are not equal")
numbers.sort() # sort() doesn't return anything
print("Sorting numbers...")
print(f"Numbers: {numbers}")
print(f"Sorted_numbers {sorted_numbers}")
if numbers == sorted_numbers:
print("The lists are equal")
else:
print("The lists are not equal")
| true |
a1cf944dad61d0af6cb3c2b753059a99e5c03951 | michalkasiarz/learn-python-programming-masterclass | /program-flow-control-in-python/GuessingGame.py | 1,059 | 4.34375 | 4 | # Challenge
# Modify the program to use a while loop, to allow the player to keep guessing.
# The program should let the player know whether to guess higher or lower, and should
# print a message when the guess is correct.
# A correct guess will terminate the program
# As an optional extra, allow the player to quit by entering 0 (zero) for the guess
import random
# assigns a random number from 1 to 10 to answer variable
highest = 10
answer = random.randint(1, highest)
print(answer) # TODO: remove after answering
print('Please guess a number between 1 and {}: '.format(highest))
guess = int(input())
while guess != answer:
if guess == 0:
print('You quit the game.')
break
elif guess < answer:
print('Too low!')
guess = int(input())
if guess == answer:
print("Well done, you guessed it!")
elif guess > answer:
print('Too high!')
guess = int(input())
if guess == answer:
print("Well done, you guessed it!")
else:
print('You got it first time!')
| true |
85ab131d6b933173455b59008d7c58a12a856b65 | michalkasiarz/learn-python-programming-masterclass | /program-flow-control-in-python/SteppingThroughForLoop.py | 347 | 4.375 | 4 | # Stepping through a For Loop
number = '63,123;321:642 941 332;120'
separators = ''
# extracting separator with a For Loop
for character in number: # for each character in a number
if not character.isnumeric(): # if is not numeric
separators = separators + character # add the character to the separators
print(separators) | true |
cbbacbba6e9a95d9751323b01d35412ed8f68e18 | SimonXu666j/pycode_learning | /实用编程技巧/类与对象相关话题/test01.py | 631 | 4.125 | 4 | #-*-coding:utf-8-*-
#如何派生内置不可变类型并修改实例化行为?
'''
解决方案:定义类Intuple继承内置tuple,并实现__new__,修改实例化行为。
'''
class IntTuple(tuple):
def __new__(cls,iterable):
#创建生成器
g=(x for x in iterable if isinstance(x,int) and x>0)
#返回一个实例化对象,传入构造器方法
return super(IntTuple,cls).__new__(cls,g)
def __init__(self,iterable):
#before
print(self)
super(IntTuple,self).__init__(iterable)
#after
t=IntTuple([1,-1,'abc',6,['x','y'],3])
print(t) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.