blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
77dd52e0b2643c3982971cd606ae1ba993d8d435 | eldss-classwork/CSC110 | /Creating Modules/oldMcDonald.py | 2,814 | 4.125 | 4 | # Evan Douglass
# HW 8: Children's Songs, the Sequel
# Grade at challenge
'''The oldMcDonald module houses several functions that can be used to write
the children's song "Old McDonald"'''
SOUNDS = []
ANIMALS = []
# Title method
# No parameters
def title():
'Outputs the song title and a blank line'
print('Old McDonald')
print()
# Verse method
# Parameters: animal and the sound it makes
def verse(animal, sound):
'Outputs a verse of the song using arguments provided'
first_last()
print('And on that farm he had', a_an(animal), animal + ',', 'E-I-E-I-O.')
SOUNDS.append(sound)
ANIMALS.append(animal)
# cycle through sounds already used
for sound in SOUNDS[::-1]:
print('With', a_an(sound), sound + '-' + sound, 'here, and',
a_an(sound), sound + '-' + sound, 'there.')
print('Here', a_an(sound), sound + ',', 'there', a_an(sound),
sound + ',','everywhere', a_an(sound), sound + '-' + sound + '.')
first_last()
print()
# Ask for another verse method
# No Parameters
def query_verse():
'''Asks the user for an animal and the sound it makes in order to output
a new verse. Five invalid tries will return False and terminate program.'''
ready_a = False
ready_s = False
count_a = 0
count_s = 0
# ask for an animal
animal = input('Enter an animal: ')
# ensure valid entry and limit to 5 tries
while not ready_a:
if 0 < count_a < 5:
animal = input('Please try again. Enter an animal: ')
elif count_a > 4:
print()
return False
if animal == '':
print('The animal cannot be blank.')
count_a += 1
elif animal in ANIMALS:
print('The animal %s has already been used.' % animal)
count_a += 1
else:
ready_a = True
# ask for a sound
sound = input('Enter the sound the animal makes: ')
# ensure valid entry and limit to 5 tries
while not ready_s:
if 0 < count_s < 5:
sound = input('Please try again. Enter a sound: ')
elif count_s > 4:
print()
return False
if sound == '':
print('The sound cannot be blank.')
count_s += 1
elif sound in SOUNDS:
print('The sound %s has already been used.' % sound)
count_s += 1
else:
ready_s = True
print()
verse(animal, sound)
return True
# Helper function for verse method
# Parameters: a word
def a_an(word):
'Modifies a sentence with a or an depending on the following word'
word = word.lower()
if word[0] in 'aeiou':
return 'an'
else:
return 'a'
# Helper function for printing first/last line in verse
# No parameters
def first_last():
'Outputs the first and last line of the verse'
print('Old McDonald had a farm, E-I-E-I-O.')
| true |
73a144d3bf620a3ea9287afd4cb713eb8fd6fab6 | zhangpengGenedock/leetcode_python | /110. Balanced Binary Tree.py | 1,901 | 4.125 | 4 | """
https://leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def helper(self, root):
if not root:
return 0, True
left_height, left_balanced = self.helper(root.left)
right_height, right_balanced = self.helper(root.right)
return max(left_height, right_height) + 1, left_balanced and right_balanced and abs(
left_height - right_height) <= 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
height, balanced = self.helper(root)
return balanced
def isBalanced2(self, root):
"""
https://discuss.leetcode.com/topic/42953/very-simple-python-solutions-iterative-and-recursive-both-beat-90
:param root:
"""
def check(root):
if not root:
return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
if __name__ == '__main__':
root = TreeNode(1)
right1 = TreeNode(2)
right2 = TreeNode(3)
root.right = right1
right1.right = right2
print Solution().isBalanced(root)
| true |
7b0811fcdf971e01cbcf0f532fb8a79d1f0c69cb | zhangpengGenedock/leetcode_python | /101. Symmetric Tree.py | 1,750 | 4.25 | 4 | # -*- coding:utf-8 -*-
__author__ = 'zhangpeng'
"""
https://leetcode.com/problems/symmetric-tree/description/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
讲解不错
offical solution: https://leetcode.com/problems/symmetric-tree/solution/
:type root: TreeNode
:rtype: bool
"""
return self.is_mirror(root, root)
def is_mirror(self, t1, t2):
if t1 is None and t2 is None:
return True
if t1 is None or t2 is None:
return False
return (t1.val == t2.val) and self.is_mirror(t1.right, t2.left) and self.is_mirror(t1.left, t2.right)
def isSymmetric2(self, root):
from collections import deque
q = deque()
q.append(root)
q.append(root)
while len(q) > 0:
t1 = q.popleft()
t2 = q.popleft()
if t1 is None and t2 is None:
continue
if t1 is None or t2 is None:
return False
if t1.val != t2.val:
return False
q.append(t1.left)
q.append(t2.right)
q.append(t1.right)
q.append(t2.left)
return True
| true |
8de2024a2a527db07a59f6ccc1efc09d9980ef70 | zhangpengGenedock/leetcode_python | /695. Max Area of Island.py | 2,409 | 4.1875 | 4 | """Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected
4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
"""
class Solution(object):
def maxAreaOfIsland(self, grid):
"""
offical solution: https://leetcode.com/problems/max-area-of-island/solution/
dfs 递归解法
:type grid: List[List[int]]
:rtype: int
"""
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0]) and (r, c) not in seen and grid[r][c]):
return 0
seen.add((r, c))
return 1 + area(r + 1, c) + area(r - 1, c) + area(r, c + 1) + area(r, c - 1)
return max(area(r, c) for r in range(len(grid)) for c in range(len(grid[0])))
def maxAreaOfIsland2(self, grid):
"""
offical solution: https://leetcode.com/problems/max-area-of-island/solution/
dfs 非递归解法
:param grid:
:return:i
"""
seen = set()
ans = 0
for r0, row in enumerate(grid):
for c0, val in enumerate(row):
if val and (r0, c0) not in seen:
shape = 0
stack = [(r0, c0)]
seen.add((r0, c0))
while stack:
r, c = stack.pop()
shape += 1
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if (0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] and (
nr, nc) not in seen):
stack.append((nr, nc))
seen.add((nr, nc))
ans = max(ans, shape)
return ans
| true |
1ff6cf2ba685fc061555a0641b048717b28efe52 | JackLu1/mks66-matrix | /matrix.py | 1,876 | 4.40625 | 4 | """
A matrix will be an N sized list of 4 element lists.
Each individual list will represent an [x, y, z, 1] point.
For multiplication purposes, consider the lists like so:
x0 x1 xn
y0 y1 yn
z0 z1 ... zn
1 1 1
"""
import math
#print the matrix such that it looks like
#the template in the top comment
def print_matrix( matrix ):
print( str(len(matrix)) + ' by ' + str(len(matrix[0])) + ' matrix' )
for i in range(0, len(matrix)):
print ' '.join(str(x) for x in matrix[i])
#turn the paramter matrix into an identity matrix
#you may assume matrix is square
def ident( matrix ):
for i in range(0, len(matrix)):
for j in range(0, len(matrix[i])):
if i == j:
matrix[i][j] = 1
else:
matrix[i][j] = 0
#return matrix
#multiply m1 by m2, modifying m2 to be the product
#m1 * m2 -> m2
#return void
# m2 is 4xn
def matrix_mult( m1, m2 ):
product = new_matrix(4, len(m2[0]))
for m1_row in range(len(m1)):
for m2_col in range(len(m2[0])):
for m2_row in range(len(m2)):
#print(m1[m1_row][m2_row])
#print(m2[m2_row][m2_col])
product[m1_row][m2_col] += m1[m1_row][m2_row] * m2[m2_row][m2_col]
return product
def new_matrix(rows = 4, cols = 4):
m = []
for r in range( rows ):
m.append( [] )
for c in range( cols ):
m[r].append( 0 )
return m
A = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
]
B = [
[11, 12, 13, 14],
[15, 16, 17, 18],
[19, 20, 21, 22],
[23, 24, 25, 26],
]
#print_matrix(A)
#print_matrix(B)
#matrix_mult(A, B)
#print_matrix(A)
#print_matrix(B)
#matrix_mult(B, A)
#print_matrix(A)
#print_matrix(B)
#ident(A)
#print_matrix(A)
#matrix_mult(A, B)
| true |
ee3d3d94e1cf31ae5d554d84c748299cb97f4c43 | esau91/Python | /Problems/leetcode/google_interview.py | 671 | 4.21875 | 4 |
def find_shortest(given_dict):
shortest = {}
iteration = 0
flag = True
while flag:
for key, value in given_dict.items():
key_len = len(key)
if iteration < key_len:
key_subs = key[:iteration]
print(key_subs)
if key_subs not in shortest:
shortest[key_subs] = shortest.get(key_subs, 1)
else:
shortest[key_subs] = shortest.get(key_subs, 1) + 1
iteration += 1
return shortest
if __name__ == '__main__':
output = find_shortest({'boat' : 1, 'car' : -1, 'candy' : 10, 'home' : 9})
print(output)
| true |
231fa24241fc27bc737aa93fc2ca3a6372404d12 | arora-yash/Python-Programming | /jumbled_words.py | 1,853 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 07:19:51 2018
@author: yashkumararora
"""
import random
def choose():
words = ['rainbow','computer','science','programming','mathematics','player','condition','reverse','water','board']
pick = random.choice(words)
return pick
def jumble(word):
jumbled="".join(random.sample(word,len(word)))
return jumbled
def thank(p1n,p2n,p1,p2):
print(p1n," your score is :",p1)
print(p2n," your score is :",p2)
print("Thanx for playing. Have a nice Day")
def play():
p1name = input("player 1 , input your name")
p2name = input("Player 2 , input yout name")
pp1 = 0
pp2 = 0
turn = 0
while(1):
#computer's task
picked_word = choose()
#create question
qn = jumble(picked_word)
print(qn)
#player1
if turn % 2 == 0:
print(p1name,"Your turn")
ans = input("What is on my mind")
if(ans == picked_word):
pp1 = pp1 + 1
print("Your score is :",pp1)
else:
print("Better luck next time I thought the word : ",picked_word)
c = int(input("Press 1 to continue and 0 to quit"))
if(c == 0):
thank(p1name,p2name,pp1,pp2)
break
else:
print(p2name,"Your turn")
ans = input("What is on my mind")
if(ans == picked_word):
pp2 = pp2 + 1
print("Your score is :",pp2)
else:
print("Better luck next time I thought the word : ",picked_word)
c = int(input("Press 1 to continue and 0 to quit"))
if(c == 0):
thank(p1name,p2name,pp1,pp2)
break
turn = turn + 1
play() | true |
85e0f87adcf9ada348c1d7874fa382c7ac669595 | bflaven/BlogArticlesExamples | /stop_starting_start_stopping/pandas_learning_basics/pandas_learning_basics_1.py | 1,923 | 4.40625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
[path]
cd /Users/brunoflaven/Documents/01_work/blog_articles/stop_starting_start_stopping/pandas_learning_basics/
[file]
python pandas_learning_basics_1.py
# source
- How to use Regex in Pandas
https://kanoki.org/2019/11/12/how-to-use-regex-in-pandas/
"""
import numpy as np
import pandas as pd
# OUTPUT_1
# df = pd.read_csv('data/world_happiness_report_2019.csv')
df = pd.read_csv('data/world_happiness_report_2019_2.csv')
# print(df)
# OUTPUT_2 (Pandas extract)
# Extract the first 5 characters of each country using ^ (start of the String) and {5}(for 5 characters) and create a new column first_five_letter
# df['first_five_Letter'] = df['Country (region)'].str.extract(r'(^w{5})')
# df.head()
# print(df.head())
# OUTPUT_3 (Pandas Count)
# First we are counting the countries starting with character ‘F’. It returns two elements but not france because the character ‘f’ here is in lower case. you can add both Upper and Lower case by using [Ff]
S = pd.Series(['Finland', 'Colombia', 'Florida', 'Japan',
'Puerto Rico', 'Russia', 'france'])
# output_3 = S[S.str.count(r'(^F.*)') == 1]
# print(output_3)
# S = pd.Series(['Finland', 'Colombia', 'Florida', 'Japan',
# 'Puerto Rico', 'Russia', 'france'])
# output_3a = S[S.str.count(r'(^[Ff].*)') == 1]
# print(output_3a)
# Total items starting with F
# S.str.count(r'(^F.*)').sum()
# output_3b = S.str.count(r'(^F.*)').sum()
# print(output_3b)
# Total items starting with F or f
# S.str.count(r'(^F.*)').sum()
# output_3c = S.str.count(r'(^[Ff].*)').sum()
# print(output_3c)
# In our Original dataframe we are finding all the Country that starts with Character ‘P’ and ‘p’ (both lower and upper case). Basically we are filtering all the rows which return count > 0.
# OUTPUT_4
output_4 = df[df['Country (region)'].str.count('^[pP].*') > 0]
print(output_4)
| true |
4d3eb71a87f04d3c0c3129f64bf8d7e51bc70a28 | Prathibha1990/python_class | /9.py | 789 | 4.4375 | 4 | # List in python
#list can hold multiple data types
#[]
x=[10,30,'lohit','prathibha','varsha']
print(x)
print(x[2])
#index or key
######
print(x[2:5])
# ['lohit', 'prathibha', 'varsha']
print(x[:3])
#till no not be print
##############
#list is mutable/change values
name=['prathibha','lohith','varsha',[2000,3455,['a']],(3424),(345)]
print(name)
print(name[1])
print(name[3])
print(name[3][1])
print(name[3][2])
#nested
name[0]='scholl'
print(name[0])
x=['prathibha','lohith','varsha',[2000,3455,['a']],(3424),(345)]
print(x[0:-1])
# ['prathibha', 'lohith', 'varsha', [2000, 3455, ['a']], 3424]
#end number count with 1, defining -
#index=0
#list=['value']
x='school','college','bca','be'
print(x)
print(x[:-2])
x='prathibhabca'
print(x[:-3])
# prathibha
############
| false |
57bc677d6e532717669fc4058f06005211dd19b3 | Prathibha1990/python_class | /19.py | 418 | 4.21875 | 4 | # Dictionaries in python
#{} we will use curly brackets
person={'name':'prathibha','age':25,'email':'prathi@'}
print(person)
print(person['name'])
print(person['age'])
person['age']=29
print(person)
# index name should not be same
x=dict(name='lohit',age=25,email='lohith@')
print(x)
person={'name':'prathibha','age':25,'email':'prathi@'}
print(person.keys())
print(person.values())
#items in dictionary
| false |
88070050081eeba6ac991e7e0f502a5e8e4978b1 | Prathibha1990/python_class | /11.py | 1,130 | 4.3125 | 4 | # tuple()
# non mutable type()
# tuples are faster compaired to list
x=(100,'lohit')
print(x)
print(type(x))
xyz=30,30.445j,'name','school'
print(xyz)
print(type(xyz))
empty_tuple=()
print(empty_tuple)
tuple1=(100,200,300)
tuple2=(100,200,300)
print(tuple1+tuple2) #it can't chanege original value
print(sum(tuple1+tuple2))
# length function
tuple10=('java','php','python','sql')
print(len(tuple10))
tuples=('john','mary','school',42556,4356,)
print(tuples[1])
# tuples[2]='lohith'
# print(tuples) #TypeError: 'tuple' object does not support item assignment
#tuple slicing()
tuples1=('john','mary','school',42556,4356,('lohit'))
print(tuples1[::-1])
print(tuples1[::2])
print('####################')
my_new_tuple=('a','b','c','d','e')
print('a' in my_new_tuple)
print('a' not in my_new_tuple)
# maximum & minimum function
list=[1,2,3,4,5,6,7,89]
print(max(list))
print(min(list))
# index function
list=[1,2,3,'prathi',5,6,7,89]
print(list.index('prathi'))
print('####################')
# count function()
list4=['prathibha','prathibha',1,3,2]
print('this counts prathibha',list4.count('prathibha'))
| false |
eaa71e3f62af7581cd31fb221f3ca86f9542c253 | ketanAggarwal58/Python | /replaceS.py | 1,153 | 4.40625 | 4 | """
The replace_ending function replaces the old string in a sentence with the new string,
but only if the sentence ends with the old string. If there is more than one occurrence
of the old string in the sentence, only the one at the end is replaced, not all of them.
For example, replace_ending("abcabc", "abc", "xyz") should
return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive,
so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made).
"""
def replace_ending(sentence, old, new):
a = sentence.find(old)
b = len(old)
c = len(sentence)
d = int(c)-int(b)
e = sentence[int(d):]
if e == old:
i = int(d)
new_sentence = sentence[:i] + e.replace(old, new)
return new_sentence
return sentence
weather = 'rainfall'
print(weather[:4])
print(replace_ending("It's raining cats and cats", "cats", "dogs"))
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts"))
print(replace_ending("The weather is nice in May", "may", "april"))
print(replace_ending("The weather is nice in May", "May", "April"))
| true |
e9e5e3c934a033c2ce0a8a1828fa5d33782452fe | ketanAggarwal58/Python | /loops.py | 373 | 4.25 | 4 | print("we have two types of loops in python");
print("1. for loop");
print("2. while loop");
print("this is an example of for loop");
for x in range(10):
print(x);
for y in range(2,10):
print(y);
print("this is an example of while loop");
i = 0;
while i < 7:
print(i);
i += 1;
if i == 5:
print("code reaches to an impass");
break; | true |
79880cd75b02737461959fa4e9c4bb4acb946506 | TejshreeLavatre/Basic-Codes | /Check Age.py | 345 | 4.1875 | 4 | #Check whether or not a person is eligible to join the 18-30 club
name = input('Hello, please enter your name: ')
print("Hello {}".format(name))
age = int(input('Please enter your age: '))
if 18 <= age < 31:
print('Welcome to the 18-30 club, {}'.format(name))
else:
print('Sorry, you aren\'t eligible for this holiday {}'.format(name))
| true |
bf5284cdd1371fc420383ddc0f5da4791edcdeda | Developernation/codefights | /cfights/python3_solutions/mexFunction.py | 971 | 4.25 | 4 | #You've just started to study impartial games, and came across an interesting theory.
#The theory is quite complicated, but it can be narrowed down to the following statements:
#solutions to all such games can be found with the mex function. Mex is an abbreviation of
#minimum excludant: for the given set s it finds the minimum non-negative integer that is not present in s.
#You don't yet know how to implement such a function efficiently, so would like to create a simplified
#version. For the given set s and given an upperBound, implement a function that will find its mex if it's
#smaller than upperBound or return upperBound instead.
#Hint: for loops also have an else clause which executes when the loop completes normally, i.e. without encountering any breaks
def mexFunction(s, upperBound):
found = -1
for i in range(upperBound):
if not i in s:
found = i
break
else:
return upperBound
return found | true |
af1e1ba7b841076f8399af7d75881c21b190f55d | Nikilesh-123/Nikilesh-Kammila | /palindromenumber.py | 329 | 4.46875 | 4 | # the palindrome in numeric
# for numeric enter the numeric character
# for example number
number = int(input("enter the string"))
string = str(number)
rev_string= string[: : -1]
print("reversed string:", rev_string)
if string == rev_string:
print("the num is palindrome: ")
else:
print("the num is not a palindrome:")
| true |
a794ae5e7412d33dda5acba1daca455fa511a603 | nicolas-git-hub/python-sololearn | /7_Object_Oriented_Programming/magic_methods.py | 1,127 | 4.6875 | 5 | # Magic methods are special methods which have double underscores at the beginning and end of their names.
# They are also known as dunders.
#
# So far, the only one we have encountered is __init__, but there are several others.
#
# They are used to create functionality that can't be represented as a normal method.
#
# One common use of them is operator overloading.
#
# This means defining operators for custom classes that allow operators such as + and * to be used on them.
#
# An example magic method is __add__ for + .
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x)
print(result.y)
# The __add__ method allows for the definition of a custom behaviour for the + operator in our class.
#
# As you can see, it adds the corresponding attributes of the objects and returns a new object
# containing the result of the class together.
#
# In other words, __add__ is a magic method that creates an instance.
| true |
c5c350e2167cb1271de5f2b3005bdde2d8a15417 | nicolas-git-hub/python-sololearn | /6_Functional_Programming/map.py | 620 | 4.375 | 4 | # The built-in function map an filter are very useful higher-order functions that operate
# on lists (or similar objects called iterables).
# The function map takes a function and an iterable as arguments, and returns a new iterable
# with the function applied to each argument.
#
# Example:
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
result = list(map(add_five, nums))
print(result)
#
# We could have archived the same result more easily by using lambda syntax.
print('\n')
result = list(map(lambda x: x + 5, nums))
print(result)
#
# To convert the result into a list, we used list explicitly.
| true |
948433a5b39c9350d3ce26f72baa2c44872bd9ba | nicolas-git-hub/python-sololearn | /5_More_Types/none.py | 883 | 4.375 | 4 | # The "None" object is used to represent the absence of a value.
# It is similar to null in other programming languages.
# Like other "empty" values, such as (), [] and the empty string,
# it is "False" when converted to a "Boolean variable".
# When entered at the Python console, it is displayed as the empty string.
print(None == None)
print(bool(None) == bool(()))
print(bool(None) == bool([]))
print(bool(None) == bool(""))
print(bool(None) == False)
# Output: True
# Considerations:
# None is an absence of a value
# None object is returned by any function that doesn't return anything else
#
# Consider:
def some_func():
print("Hi")
var = some_func()
print(var)
# This outputs "Hi" and "None"
# ==============================
# Another example:
foo = print()
if foo == None:
print(1)
else:
print(2)
# It outputs "1" because function print() returns None
| true |
dad02800e2723cc1ef2ffdcef944ac63361c0514 | nicolas-git-hub/python-sololearn | /6_Functional_Programming/recursion.py | 1,782 | 4.5625 | 5 | # Recursion is a very important concept in functional programming.
# The funcdamental part of recursion is self-reference - function calling themselves.
# It is used to solve problems that can be broken up into easier sub-problems of the same type.
#
# A classic example of a function that is implemented recursively is the factorial function, which
# finds the product of all positive integers below a specific number.
#
# For example, 5! (5 factorial) is 5 * 4 * 3 * 2 * 1 (120).
#
# To implement this recursively, notice that 5! = 5 * 4!, 4! = 4 * 3!, 3! = 3 * 2!, and so on.
# Generaly, n! = n * (n-1)! .
#
# Futhermore, 1! = 1. This is known as the base case, as it can be calculated without performing any
# any more factorials.
# Below is a recursive implementation of the factorial function.
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x - 1)
print(factorial(5))
# The base case acts as the exit condition of the recursion.
# Recursive functions can be infinite, just like infinite while loops.
# These often occur when you forget to implement the base case.
# Below is an incorrect version of the factorial function.
# It has no base case, so it runs until the interpreter runs out of memory an crashes.
# def my_factorial(x): # Block commented so the rest of the script could run.
# return x * my_factorial(x - 1)
# print(my_factorial(5))
#
# Recursion can also be indirect.
# One function can call a second, which calls the first, which calls the second, and so on.
# This occur with any number of functions.
#
# Example:
def is_even(x):
if x == 0:
return True
else:
return is_odd(x - 1)
def is_odd(x):
return not is_even(x)
print(is_odd(17))
print(is_even(23))
| true |
659a5e141cc44c7e9f530bf103df12e6ddf1f0f5 | nicolas-git-hub/python-sololearn | /6_Functional_Programming/functional_programming.py | 1,836 | 4.4375 | 4 | # Functional programming is a style of programming that (as the name suggests) is
# based around functions.
# A key part of functional programming is higher-order functions. We have seen this idea
# briefly in the previous lesson on functions as objects.
# Higher-order functions take other functions as arguments, or return them as results.
#
# Example:
def apply_twice(func, arg):
return func(func(arg))
def add_five(x):
return x + 5
print(apply_twice(add_five, 10))
# The function apply_twice takes another function as its argument and calls it twice inside its body.
#
# Pure functions
#
# Functional programming seeks to use pure functions.
# Pure functions have no side effects, and return a value that depends only on their arguments.
# This is how functions in math work: for example, the cos(x) will, for the same value of x, always
# return the same result.
# Below are examples of pure and impure functions.
#
# Pure functions:
#
def pure_function(x, y):
temp = x + 2 * y
return temp / (2 * x + y)
#
# Impure function:
#
some_list = []
def impure(arg):
some_list.append(arg)
#
# The function above is not pure, because it changed the state of some_list
#
# Pure functions has both advantages and disavantages:
#
# Pure functions are:
# - easier to reason about and test;
# - more efficient. # Once the function has been evaluated for an input, the result can be stored
# and refered to the next time the function of that input is needed, reducing
# the number of times the function is called.
# This is called memorization.
# - easier to run in parallel.
#
# The main disavantage of using only pure functions is that they mojorly complicate the otherwise
# simple task of I/O since this appears to inherently require side effects.
# They can also be more difficult to write in some situations.
| true |
ac68e238a4ad576c4fd33580a9e28f8828ba30e8 | btranscend/numericalIntegration | /polynomial.py | 2,936 | 4.28125 | 4 | #!/usr/bin/python3
import unittest
class Polynomial(object):
# Constructor where the object
# is the degree of a given polynomial
def __init__(self, degree):
self.degree = degree
self.coef = []
# Constructor where the object is
# are the coefficients of a given polynomial
def setCoef(self, coef):
# the number of coeffecients is one more than the degree number
if len(coef) == self.degree+1:
self.coef = coef
# method for evaluating x to the degreeth power times the degree of the last given coeffecient
def evaluate(self, x):
result = 0
degree = self.degree
# while the degree is not less than 0
while not degree < 0:
# result is x to the given degree'th power times the given degree of the last given coeffecient
result += (x**degree)*self.coef[degree]
# the degrees in a polynomial function decrement by 1
degree -= 1
# return x^given degree'th power times the given coeffecient
return result
# method for evaluating the antiderivative of a polynomial function
def find_anti(self):
# variable set to one more than the degree
degree = self.degree+1
# variable set to the polynomical function
# with given object degree passed in
anti_derivative = Polynomial(degree)
# initialized counter at 0
counter = 0
# initialized variable for new coeffecient at empty array
new_coef = []
# while the degree is not 0
while not degree == 0:
# add the last given coeffeciecnt divided by the given degree
# to the empty array as new coeffecient
new_coef.append(self.coef[counter]/degree)
# degrees decrement by 1 in a polynomial function
degree -= 1
# counter increments by 1 for the last coeffecient
counter += 1
# adding 0 to the array- new coeffecient -
new_coef.append(0)
# pass the new coeffecient to the polynomial function
anti_derivative.setCoef(new_coef)
# return the antiderivative
return anti_derivative
if __name__ == '__main__':
class TestPolynomial(unittest.TestCase):
# test different degrees method
def test_degree(self):
poly = Polynomial(2)
self.assertEqual(poly.degree, 2)
# test different coeffecients method
def test_coef(self):
poly = Polynomial(2)
poly.setCoef([1, 2, 1])
self.assertEqual(poly.coef, [1, 2, 1])
# test evaluation method
def test_eval(self):
poly = Polynomial(2)
poly.setCoef([1, 2, 1])
self.assertEqual(poly.evaluate(2), 9)
# test anti_derivative method
def test_anti(self):
poly = Polynomial(2)
poly.setCoef([1, 2, 1])
anti = Polynomial(3)
anti.setCoef([1/3, 1, 1, 0])
self.assertEqual(poly.find_anti().coef, anti.coef, poly.find_anti().degree)
unittest.main() | true |
5b8f515e09a50e5d5ffb32838447cd191abdee48 | justinnhli/wernicke | /sample.py | 1,010 | 4.21875 | 4 | if False:
print ("false")
elif True:
print ("true")
else:
print ("should not print")
#
# if 1 > 0 :
# print ('case 1 correct')
# else:
# print ('case 1 incorrect')
#
# if 1 < 0 :
# print ('case 2 incorrect')
# else:
# print ('case 2 correct')
#
# if 0 < 1 < 2:
# print('case 3 correct')
# else:
# print('case 3 incorrect')
#
# myBool = True
#
# if myBool:
# print ('case 4 correct')
# myBool = False
# else:
# print ('case 4 incorrect')
# a = 0
# while a < 10:
# print(a)
# a += 1
print(True and True)
print(True and False)
print(False and True)
print(False and False)
print()
print(True or True)
print(True or False)
print(False or True)
print(False or False)
print()
print(not True)
print(not False)
# print(2 * 3 + 4)
# print(2 + 3 * 4)
# print(2 * 3 - 4)
# print(2 - 3 * 4)
# print(4 / 2 + 1)
# print(4 + 2 / 2)
# print(4 + 2 / 2 + 9)
# #print(4 + 2 * 2 + 9)
# print("hello world")
# a = 1
# print(a)
# print(a)
# print(a)
#
# print (110 % 2)
| false |
41a4078846aa79ef78e52222579342583d0db329 | HarshithaReddyJ/1026-Harshitha-Reddy- | /module5(assignment2).py | 2,038 | 4.78125 | 5 | # 1. Write a python program to create a tuple...
x = () # create an empty tuple
print(x)
tupleb = tuple() # create an empty tuple with tuple() function built-in python.
print(tupleb)
# 2.Write a python program to create a tuple with different data types...
# Type-1 :
tupleb = ("tuple",True,10.0,5)
print(tupleb)
# Type-2 :
# an empty tuple :
t = ( )
print(t)
# tuple with items :
tuple = ('python' , 'tuple')
print(tuple)
# concatenating 2 tuples :
tuple1 = (0,1,2,3)
tuple2 = ('python','program')
print(tuple1 + tuple2)
# nested tuples :
tuple1 = (0,1,2,3)
tuple2 = ('python','program')
tuple3 = (tuple1,tuple2)
print(tuple3)
# tuple repitition :
tuple1 = ('python',)*3
print(tuple1)
# tuples are immutable :
tuple1 = (0,1,2,3)
print(tuple1)
# length of a tuple :
tuple1 = ('python','program')
print(len(tuple1))
# 3.Write a python program to convert tuple to a string...
tuple = ('p','y','t','h','o','n')
str = ''.join(tuple)
print(str)
# 4.Write a python program to slice a tuple...
tuples = (1,2,3,4,5,6,7,8,9)
slice = tuples[3:5]
print(slice)
tuples = (1,2,3,4,5,6,7,8,9)
slice = tuples[:]
print(slice)
tuples = (1,2,3,4,5,6,7,8,9)
slice = tuples[-8:-4]
print(slice)
# 5. Write a python program to find the length of a tuple...
tuple1 = tuple("python")
print(tuple1)
print("The length of a tuple is : " ,len(tuple1))
# 6. Write a python program to convert tuple to a dictionary...
tuplex = ((2,"b"),(3,"s"))
print(dict((y,x) for x , y in tuplex))
# 7.Write a python program to reverse a tuple...
x = ("python")
y = reversed(x)
print(tuple(y))
# 8. Write a python program to convert a list of tuples into a dictionary...
l = [("b",1) , ("s",2) , ("r",3)]
d = { }
for a , b in l :
d.setdefault(a,[ ]).append(b)
print(d)
# 9. Write a python program to convert a list to a tuple...
# Type-1 :
listx = [1,2,3,4,5]
print(listx)
tuplex = tuple(listx)
print(tuplex)
# Type-2 :
def convert(list) :
return tuple(list)
list = [1,2,3]
print(convert(list)) | false |
e67547d2156ec0a913d048b4643ad6b1d8b380aa | pankaj-pundir/The-projects | /dexterous/3danim_example.py | 2,576 | 4.40625 | 4 | """
============
3D animation
============
A simple example of an animated plot... In 3D!
"""
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
def Gen_RandLine(length, dims=2):
"""
Create a line using a random walk algorithm
length is the number of points for the line.
dims is the number of dimensions the line has.
"""
lineData = np.empty((dims, length))
lineData[:, 0] = np.random.rand(dims)
for index in range(1, length):
# scaling the random numbers by 0.1 so
# movement is small compared to position.
# subtraction by 0.5 is to change the range to [-0.5, 0.5]
# to allow a line to move backwards.
step = ((np.random.rand(dims) - 0.5) * 0.1)
lineData[:, index] = lineData[:, index - 1] + step
return lineData
def update_lines(num, dataLines, lines):
for line, data in zip(lines, dataLines):
# NOTE: there is no .set_data() for 3 dim data...
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
return lines
# Attaching 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)
graph_data=open("data.txt",'r').read()
lines=graph_data.split('\n')
xs=[]
ys=[]
zs=[]
ts=[]
v=[0.0 for i in range(4)]
pr=[0.0 for i in range(4)]
pan=[0.0 for i in range(4)]
#plt.axon()
for l in range(1,len(lines)-1):
z=list(map(lambda x:(float(x)),lines[l].split(',')))
tnew=int(z[0])
#lambda x:(float(x)*100)//10
#print(z)
#print(str(x)+str(y)+str(z))
#ts.append(t)
#print(type(z[1]))
time=(tnew-int(lines[l-1].split(',')[0]))/100
for b in range(1,4):
pan[b]+=(z[b])
if b==4:
v[b]=0
else:
v[b]=pan[b]
print(str(z[3])+" "+str(pan[3]))
xs.append(v[1])
ys.append(v[2])
zs.append(v[3])
for b in range(4):
pr[b]=z[b]
# Fifty lines of random 3-D lines
#data = [Gen_RandLine(25, 3) for index in range(1)]
# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
#lines = [ax.plot(xs[dat],ys[dat],zs[dat])[0] for dat in range(len(lines)-1)]
ax.plot(xs,ys,zs)
# Setting the axes properties
#ax.set_xlim3d([0.0, 1.0])
ax.set_xlabel('X')
#ax.set_ylim3d([0.0, 1.0])
ax.set_ylabel('Y')
#ax.set_zlim3d([0.0, 1.0])
ax.set_zlabel('Z')
ax.set_title('3D Test')
# Creating the Animation object
line_ani = animation.FuncAnimation(fig, update_lines, 25,
interval=50, blit=False)
plt.show() | true |
54cd3f14708ee889f563c0f84c0817f69857a451 | eeyoo/python | /src/function.py | 742 | 4.28125 | 4 | #! /usr/bin/python
# function without return statement
def fib(n):
"""Print a Fibonacci series up to n."""
a,b = 0, 1
while a < n:
print a,
a, b = b, a+b
# call fib function
print 'fib(2000)'
raw_input('press any to continue...')
fib(2000)
# assign fib to another name
f = fib
print '\nfib(0) = ?'
raw_input('press any to continue...')
print f(0)
# hold on
raw_input('press any to continue...')
# function return list
def fib2(n):
"""Return a list containing the Fibonacci up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
# call fib2
print 'f100 = fib2(1000)'
raw_input('press any to continue...')
f100 = fib2(1000)
print f100
| true |
391b35097d6ff5d3f4194f27dcf0bfdc7d9587c5 | Philip-Loeffler/python | /SectionTen/OOPandClassesPT2.py | 1,556 | 4.46875 | 4 | # this section is entitled "instances, constructors, sets and more"
# class: template for creating obects. all objects created using the same class will have the same characterists
# object: an instance of a class
# instantiate: create an instance of a class
# method: a function defined in a class
# attribute: a variable bound to an instance of a class
# in python, every type is a class
# the init method is the constructor
class Kettle(object):
def __init__(self, make, price):
self.make = make
self.price = price
self.on = False
# functions that are bound to a class are called methods. and the main difference is the presence of the self parameter
# self is similar to this.on in java
# self is a reference to the instance of the class
def switch_on(self):
self.on = True
kenwood = Kettle("Kenwood", 8.99)
hamilton = Kettle("hamilton", 14.55)
# because kenwood and hamilton are objects, we can replace them in the attribute fields
print("models: {0.make} = {0.price}, {1.make} = {1.price}".format(
kenwood, hamilton))
# when we run hamilton here, it will be false
print(hamilton.on)
hamilton.switch_on()
# then when we run it here, after the switch function is called, it will come back as true
print(hamilton.on)
Kettle.switch_on(kenwood)
print(kenwood.on)
kenwood.switch_on()
print("*" * 80)
# power is bound to the instance of the kenwood class
kenwood.power = 1.5
print(kenwood.power)
# power will not be availabe on hamilton, since it hasnt been added to this instance
print(hamilton.power)
| true |
1831cdeeb37ef3058db155431c00059a138ad5f3 | Philip-Loeffler/python | /SectionFour/nestedForLoops.py | 323 | 4.21875 | 4 | for i in range(1, 13):
for j in range(1, 13):
print("{0} times {1} is {2}".format(j, i, i * j))
print("--------------")
# first loop runs 1 time, then inner loop will run all the way through
# then come back to the outer loop, which then again but incremented one time
# and inner loops runs through fully
| true |
8d6be190063a8dbbcc4cb9637db8801429a2e676 | Philip-Loeffler/python | /SectionFive/sortingList.py | 576 | 4.6875 | 5 |
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
# extend will combine and add all of the iterables from the list and adds them to it
even.extend(odd)
print(even)
# sort will sort the sequence of numbers
# sort method doesnt create a copy of the list, it rearranges the items of the list
# lists are mutable and their contents can be changed
even.sort()
print(even)
another_even = even
# same list printed out twice,
print(another_even)
# will sort in the reverse order
even.sort(reverse=True)
print(even)
# this list will be reversed because of mutability
print(another_even)
| true |
3dc389c7dadea1293fd13bdc0127a166e9815867 | Philip-Loeffler/python | /SectionFour/in&NotInConditions.py | 468 | 4.15625 | 4 | parrot = "Norweigian blue"
letter = input("enter a character: ")
# checking to see if a letter is in parrot
if letter in parrot:
print("{} is in {}".format(letter, parrot))
else:
print("i dont need that letter")
# here is using not
activity = input("What would you like to do today ")
# checking to see if cinema is in the activity variable. this is also case sensitive
if "cinema" not in activity.casefold():
print("But i want to go to the cinema")
| true |
8313c2cf9fe5a1c478d690ddad54cdb7d459c56c | Philip-Loeffler/python | /SectionFive/nestedLists.py | 815 | 4.3125 | 4 | empty_list = []
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = [even, odd]
# this will print out [[2,4,6,8], [1,3,5,7,9]]
# you have a list within a list
print(numbers)
# will create the 2 seperate lists and print them out
for number_list in numbers:
print(number_list)
# will print out the values inside those 2 lists
for value in number_list:
print(value)
menu = [
["eggs", "bacon"],
["eggs", "sausage", "bacon"],
["eggs", "spam"],
["eggs, sausage", "spam", "bacon", "spam", "tomato", "spam"],
]
# this will print only the meals that dont contain spam
for meal in menu:
if "spam" not in meal:
print(meal)
for item in meal:
print(item)
else:
print("{0} has a spam score of {1}"
.format(meal, meal.count("spam")))
| true |
cc96e31133f2e20a9563adc61c970b233fb1e010 | perrym6949/CTI110 | /P3HW1_Debugging_Perry.py | 580 | 4.1875 | 4 | # System Grading Output
# 3/23/2021
# CTI-110 P3HW1-Debugging
# Madelyn Perry
#
def main():
# Program takes number grade and outputs letter grade.
# Use 10-point grading scale:
A = 90
B = 80
C = 70
D = 60
F = 50
score = input('Please input your grade: ')
Grd = int(score) # Grd <-- Grade
if Grd>=90:
print('Your grade is: A.')
elif Grd>=80:
print('Your grade is: B.')
elif Grd>=70:
print('Your grade is: C.')
elif Grd>=60:
print('Your grade is: D.')
else:
print('Your grade is: F.')
main()
| true |
a9aab3bd27a47191ecfe88770ca5a41cf97d0324 | steve-yuan-8276/pythonScrapy | /practiceFolder/runoob/datetime_16.py | 341 | 4.28125 | 4 | # 题目:输出指定格式的日期。
#
# 分析:此题实际是要求学习time 模块的用法
import time, datetime
# today
print(time.strftime("%Y, %m, %d"))
print(datetime.date.today())
# yesterday
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
print(f"Yesterday is {yesterday}.")
| false |
78cd91b1ab16e08d3057757ed6e47960d6eafeee | steve-yuan-8276/pythonScrapy | /practiceFolder/ComputerProgrammingforKids/area_or_perimeter.py | 538 | 4.3125 | 4 | length = int(input("Please input the length(cm): "))
width = int(input("Please input the width(cm): "))
def area_of_the_rectangle(length, width):
area_of_the_rectangle = length * width
return area_of_the_rectangle
def perimeter_of_the_rectangle(length, width):
perimeter_of_the_rectangle = (length + width)*2
return perimeter_of_the_rectangle
print(f"The area of the rectangle is {area_of_the_rectangle(length, width)} cm² .")
print(f"The perimeter of rhe rectangle is {perimeter_of_the_rectangle(length, width)} cm.") | true |
b5f319cd9f4748295a89f14c6090a51fd10a93a2 | TheShrug/Advent-of-Code | /day2/day-2-1.py | 791 | 4.21875 | 4 | def contains_count_of_any_letter(string, count):
""" Returns bool of whether or not the provided
string contains count number of any unique letter.
This could be optimized further to prevent unnecessary
processing.
:param string:
:param count:
:return bool:
"""
for char in string:
if string.count(char) == count:
return True
return False
countContainsTwo = 0
countContainsThree = 0
file = open("input.txt")
for line in file:
"""
These could be done in one function that returns a pair of booleans ¯\_(ツ)_/¯
"""
if contains_count_of_any_letter(line, 2):
countContainsTwo += 1
if contains_count_of_any_letter(line, 3):
countContainsThree += 1
print(countContainsTwo * countContainsThree)
| true |
4fb3c69cf7196c8cd8251eb5b46e6a98fdfc27da | emmanuelrobles/School | /Python/Harvard/Assigment 5/pairs.py | 1,749 | 4.125 | 4 | """
1) Using the English DictionaryPreview the documentView in a new window that Downey provides, find all words in the dictionary whose reverse is also in the dictionary. There are about 500 such unordered pairs: build a list with each pair appearing once in alphabetic order. Your list should start with the pair ('aa', 'aa') and end with the pair ('yay', 'yay') and should include ('abut', 'tuba') but not ('tuba', abut').
Have your program print the number of such pairs, and print the first 10 pairs.
"""
import sys
def reverse(word):
word_Reversed=""
for charac in word[::-1]:
word_Reversed+=charac
return word_Reversed
dict_words_rever={}
file="words.txt"
if len(sys.argv)==2:#if there is a console input file will be the path
file= sys.argv[1]
try:
with open(file,"r") as f:
for lin in f:
key=lin[:-1]# get rid of newLine char
val=reverse(key)
dict_words_rever[key]=val# fromat key= word val= word_reversed
dict_done={}
for word in dict_words_rever:
if (dict_words_rever[word] in dict_words_rever) and (dict_words_rever[word] not in dict_done): #get rid of dupli
dict_done[word]= dict_words_rever[word]
for i,key in enumerate(sorted(dict_done)):
if(i==10):
break
else:
print("{0}: {1} {2}".format(i+1,key,dict_done[key]))
except FileNotFoundError:
print("File not found")
exit(1)
except:
print("Something went wrong")
exit(1)
"""""
#another way
list_pairs=[]
for keys in dict_done:
list_pairs.append(keys+" "+dict_done[keys])
list_pairs.sort()
for i in range(1,11):
print(str(i)+" "+list_pairs[i])
"""
| true |
5b28fec3335efd32d3768942c39e2d72b4725838 | NikitaChhattani/sdet | /python/Activity11.py | 235 | 4.28125 | 4 |
fruits={
"Mango" :10,
"Banana" :30,
"Apple" :40,
"Kiwi" :40,
}
choice=input("Enter fruit name you are looking for :")
for fruit in fruits:
if(fruit==choice):
print(choice,"is available")
| false |
11ebd324957354748a4cc483fb8bb74075c68556 | COrtaDev/Data-Structures-and-Algorithms | /HackerRank/InterviewPrep/ProblemSolving/theMaximumSubArray/maxSubArr.py | 2,451 | 4.1875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxSubarray function below.
def maxSubarray(arr):
# the subarray will be a slice of the array where all elements are contiguous
# the subsequence however are elements that are non contiguous
# we observe that if all elements are negative the max subseqence therefore is the
# largest negative number aka: the number closest to 0.
# we observe that if all the numbers are positive, the max sum will be the sum of all
# elements in that array.
# we observe that the maximum subsequence can be found by removing all negative numbers for the
# array and summing them together
# the most time-complex behavior will be associated with finding the subarray sum of all subarrays
# in a given array and returning the max sum of that subarray
# Currently we time out for certain test cases, they must be extremely long arrays
# We will look for optimizations first
# if(len(arr) >= 50000):
# print(len(arr))
# return
print(len(arr))
# The following code is adequate for all but 1 test case:
maxSubArrSum = sum(arr)
# This handles finding the max subArr sum:
for i in range(len(arr)):
for j in range(len(arr), i, -1):
currentSum = sum(arr[i:j])
if maxSubArrSum < currentSum:
maxSubArrSum = currentSum
arr.sort()
# We can peek at the first and last elements of the sorted array
# If they are both positive we can return the sum of the entire array
if arr[0] > 0: # When the first element is larger than 0, every element is therefore positive
return maxSubArrSum, sum(arr)
if arr[-1] < 0: # When the last element is negative, it will be the largest int in the array
return maxSubArrSum, arr[-1]
# At this point we have an array of negative and positive numbers
# We will iterate through the array and find the first postive value
for k in range(1, len(arr)):
if arr[k] > 0:
return maxSubArrSum, sum(arr[k:len(arr)])
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
arr = list(map(int, input().rstrip().split()))
result = maxSubarray(arr)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
9bcfb99ff91f61a3e715e030072624156317acc9 | candiepih/alx-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,499 | 4.15625 | 4 | #!/usr/bin/python3
"""Contains `Square` class defination"""
from .rectangle import Rectangle
class Square(Rectangle):
"""Class inherits from `Rectangle` class"""
def __init__(self, size, x=0, y=0, id=None):
"""Initializes instance attributes
Args:
size (int): size of rectangle
x (int): x axis of rectangle
y (int): y axis of the rectangle
id (int): id of the rectangle
"""
super().__init__(size, size, x, y, id)
@property
def size(self):
"""Retrieves the value of `size`
Returns:
value of size
"""
return self.width
@size.setter
def size(self, value):
"""sets the dimensions of `Square`"""
self.width = value
self.height = value
def update(self, *args, **kwargs):
"""Updates the values of the class"""
if args and len(args) > 0:
keys = ["id", "size", "x", "y"]
for i, v in enumerate(args):
setattr(self, keys[i], v)
else:
for k, v in kwargs.items():
setattr(self, k, v)
def to_dictionary(self):
"""Retrieves all the attributes of class to dictionary
Returns:
dictionary containing it's attributes
"""
dictionary = {
"id": self.id,
"size": self.size,
"x": self.x,
"y": self.y
}
return dictionary
| true |
8a452b2ec4376064b51e01e191cc92a38c64d263 | candiepih/alx-higher_level_programming | /0x06-python-classes/2-square.py | 622 | 4.46875 | 4 | #!/usr/bin/python3
"""Represent a square class"""
class Square:
"""Derives a square """
def __init__(self, size=0):
"""Initializes the data
Args:
size (int): size of the square
Note:
Do not include the `self` parameter in the ``Args`` section.
Raises:
TypeError: when `size` isn't an integer
ValueError: `size` is less than 0
"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
if (size < 0):
raise ValueError("size must be >= 0")
self.__size = size
| true |
37ec3b0724e970e6b7e9cb5f2af524fc2985f1db | keertanaganiga/Lockdown_coding | /reverse.py | 298 | 4.21875 | 4 | '''
Reverse words in a given String in Python We are given a string and we need to reverse words of given string ?
Examples:
Input :
str = "AIET CHALLENGES IIT"
Output :
str = "IIT CHALLENGES AIET"
'''
str1="AIET CHALLENGES IIT"
print(str1[::-1])
'''
another solution:
str1=input()
print(str1[::-1])
''' | true |
cea99b8e2289e57e6de606356ef75d8cdc862f24 | gishbg/my_pynet | /CL1ex7.py | 850 | 4.375 | 4 | #!/usr/bin/env
"""
7. Write a Python program that reads both the YAML file and the JSON file created in exercise6 and pretty prints the data structure that is returned.
"""
from __future__ import print_function, unicode_literals
import yaml
import json
from pprint import pprint
def output_format(my_list, file_type):
pprint("")
pprint("#"*30)
pprint(file_type)
pprint("#"*30)
pprint(my_list)
pprint("#"*30)
pprint("")
def main():
"""
7. Write a Python program that reads both the YAML file and the JSON file created in exercise6 and pretty prints the data structure that is returned.
"""
with open("yaml_file.yaml") as f1:
yaml_list = yaml.load(f1)
with open("json_file.json") as f2:
json_list = json.load(f2)
output_format(yaml_list, "YAML FILE")
output_format(json_list, "JSON FILE")
if __name__ == "__main__":
main()
| true |
259c1a81fdc5a7e7b731daf4a6aab6dba03dc649 | SonikaVashistha/python-practice | /basics/com/shanu/Circle.py | 370 | 4.21875 | 4 | from math import pi
r=2
# area of circle up to 2 decimal places
print("Area of circle with radius", str(r), "is", round(pi*r**2,2))
# area of circle up to 4 decimal places
print("Area of circle with radius", str(r), "is", '%.4f'%(pi*r**2))
# circumference of circle upto 2 decimal places
print("Circumference of the circle with radius", str(r), "is", '%.2f'%(2*pi*r)) | true |
87cff0de5eafdf4641444a16a7273a6697a087b8 | SteffiBaumgart/Computer_Science_1 | /pairs.py | 553 | 4.21875 | 4 | #uses a recursive function to count the number of pairs of repeated characters in a string. Pairs of characters cannot overlap.
# Steffi Baumgart
# 1 May 2015
def main():
message = input("Enter a message: \n")
print("Number of pairs: " + pair(message, 0))
def pair (message, count):
if len(message) < 2:
return str(count)
char = message[0]
if message[0] == message[1]:
count+=1
return pair(message[2:], count)
else: return pair(message[1:], count)
if __name__ == "__main__":
main()
| true |
589ff52e3b645b897dfbbffe31fcf46adbfb8cbc | SteffiBaumgart/Computer_Science_1 | /palindromeprime.py | 710 | 4.125 | 4 | # Finding all palindromic primes between two integers
# Steffi Baumgart
# 23 March 2015
N = eval(input("Enter the start point N:" +"\n"))
M = eval(input("Enter the end point M:" + "\n"))
print("The palindromic primes are:")
#loop from M to N
if (N < 2):
N = 1
for i in range (N+1, M):
#Check if Palindromic
revNum = str(i)
if revNum[::-1] == str(i):
#Check if Prime
check = True
for k in range (2,i):
if (i%k==0):
check = False
if (i==1):
check = False
if check == True:
print(i)
| false |
43d42ae79ca535deb5c4ccede2474f6ee83bcf48 | everbird/leetcode-py | /2013/convert-sorted-list-to-binary-search-tree.py | 1,554 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class ListNode(object):
next = None
value = 0
def __init__(self, value, next=None):
self.value = value
self.next = next
class TreeNode(object):
left = None
right = None
value = 0
depth = 0
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_bst(node, start, end):
if start > end:
return None, node
mid = (start + end) / 2
left, node = build_bst(node, start, mid-1)
parent = TreeNode(node.value, left=left)
node = node.next
parent.right, node = build_bst(node, mid+1, end)
return parent, node
def get_list_length(head):
length = 0
node = head
while node:
node = node.next
length += 1
return length
def print_bst(root):
queue = []
queue.append(root)
pre = -1
while queue:
node = queue.pop(0)
if node.depth != pre:
print '\n',
print node.value,
if node.left:
node.left.depth = node.depth + 1
queue.append(node.left)
if node.right:
node.right.depth = node.depth + 1
queue.append(node.right)
pre = node.depth
def run():
a = ListNode(3)
b = ListNode(2, next=a)
c = ListNode(1, next=b)
head = c
length = get_list_length(head)
tree_head, _ = build_bst(head, 0, length - 1)
print print_bst(tree_head)
if __name__ == '__main__':
run()
| true |
aecae5acc5d8ddd02c2667c69ee53a1fa50606e8 | SinghJitender/Python | /Hackerrank/lists.py | 1,676 | 4.46875 | 4 | '''
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
'''
N = int(input())
listOfItems = list()
for x in range(0 ,N):
process = input().split(" ")
if len(process) == 3 :
listOfItems.insert(int(process[1]) ,int(process[2]))
elif len(process) == 2 :
if process[0] == "remove" :
listOfItems.remove(int(process[1]))
else :
listOfItems.append(int(process[1]))
else :
if process[0] == "sort" :
listOfItems.sort()
elif process[0] == "print" :
print(listOfItems)
elif process[0] == "pop" :
listOfItems.pop()
elif process[0] == "reverse" :
listOfItems.reverse()
| true |
ed5d56877cb4be73f548bf20c5d0ee72715f2190 | SinghJitender/Python | /ControlFlowStatements/ForLoop.py | 449 | 4.3125 | 4 | # For iterating over the elements
list =[1,2,3,4,5,6,7,8,9,10]
for num in list:
print(num)
str = "This is a string"
for letter in str:
print(letter,end='_')
# tuple unpacking
list =[(1,2),(3,4),(5,6),(7,8)]
for tuple in list:
print(tuple)
for a,b in list:
print(a)
print(b)
d={'k1':1,'k2':2,'k3':3}
for item in d:
print(item)
for item in d.items():
print(item)
for key,value in d.items():
print(f"{key}:{value}")
| true |
94ecf79c8b7d707aceab8db8a4c0a4c45ac5b8f8 | SinghJitender/Python | /ObjectsAndDataStructures/ListAndDictionary.py | 1,431 | 4.21875 | 4 | # list are similar to arrays in python. they can hold any type of data and supports indexing and slicing function juts as string
list = [1,2,3,4,5]
print(list)
list = ["one","two",'three']
print(list)
list = ["One",120,133.45]
print(list)
list = [1,2,3,4,5]
print(list[0]) # items at index - 0
print(list[1:]) # All items starting from index 1
print(len(list)) # length of list
list += [6,7,8] # adding elements/ concatenating list to another list
print(list)
# Python provides alot of inbuilt methods such as sort(), reverse(), pop(), append()
list.sort()
print(list) # prints sorted list. sort() method do not return anything, it sorts the original list
list.reverse()
print(list)
list.append(9) # adds element to the end of list
print(list)
item1 = list.pop() # removes last element
item2 = list.pop(0) # remove element with the index provided. By default its -1;
print(f"{item1} and {item2}")
print(list)
x = None # Null as in Java
# Dictionaries are just like Hashtables
dictionary = {'key1':100, 'key2':200, 'key3':300}
print(dictionary)
print(dictionary['key2']) # prints value of key 2;
dictionary = {'key1':130.30, 'key2':[10,20,30], "key3":{'insideKey':200}}
print(dictionary)
print(dictionary['key2'])
print(dictionary['key3']['insideKey'])
dictionary['key4'] = 6969.69 # adding new key to dictionary
print(dictionary)
print(dictionary.values())
print(dictionary.keys())
print(dictionary.items()) # returns tuple
| true |
2d2739e330eab90653f90240664d2c3940ed10fc | SinghJitender/Python | /MethodsAndFunctions/LambdaExpression.py | 720 | 4.46875 | 4 | # map() and filter()
# lambda expression are anonymous functions
# map() is used to map each item in the list to the given function and returns a list
def sqrt(num):
return num**2
mylist = [1,2,3,4,5]
print(list(map(sqrt,mylist)))
#filter() can be used to filter the list based upon a condition
def check_len(str):
return len(str)%2==0
list_names=["Jitender","Jitu","Jagii","Amit"]
print(list(filter(check_len,list_names)))
# Converting normal methods into lambda expression
# def function_name(parameter):
# return expression
# To lambda expression
# lambda parameter: expression
var = lambda str: len(str)%2==0
print(var("ABC"))
print(list(filter(lambda str:str[0].lower() in "aeiou", list_names)))
| true |
c11398aadb3f3da34439229f95449f0f01087330 | ncrowder/python-programming-edX | /assignment3.py | 1,858 | 4.1875 | 4 | # This function accepts a 2-dimensional list of characters (like a crossword puzzle) and a string (word) as input arguments.
# It searches the rows and columns of the 2d list to find a match for the word.
# If a match is found, this functions capitalizes the matched characters in 2-dimensional list and returns the list.
# If no match is found, this function simply returns the original 2-dimensional list with no modification.
def find_word_horizontal(crosswords,word):
lines=[]
for num in range(len(crosswords)):
line=''.join(crosswords[num])
lines.append(line)
for num in range(len(lines)):
if word in lines[num]:
position = lines[num].find(word)
if position != -1:
return([num,position])
return(None)
def find_word_vertical(crosswords, word):
lines=[]
for col in range(len(crosswords[0])):
line=''
for row in range(len(crosswords)):
line = line + crosswords[row][col]
lines.append(line)
for col in range(len(lines)):
if word in lines[col]:
specific_row = lines[col].find(word)
if specific_row != -1:
return([specific_row,col])
return(None)
def capitalize_word_in_crossword(crosswords,word):
wordlength = len(word)
horizontal = find_word_horizontal(crosswords,word)
vertical = find_word_vertical(crosswords,word)
if horizontal != None:
row = horizontal[0]
col = horizontal[1]
for n in range(wordlength):
crosswords[row][col+n]=crosswords[row][col+n].upper()
return(crosswords)
if vertical != None:
row = vertical[0]
col = vertical[1]
for n in range(0,wordlength):
crosswords[row+n][col]=crosswords[row+n][col].upper()
return(crosswords)
return(crosswords)
| true |
80397fd2494793f67e7966ead0de4fd3e3f0ce0b | lvfds/Curso_Python3 | /mundo_2/desafio_067.py | 836 | 4.15625 | 4 | """
Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário.
O programa será interrompido quando o número solicitado for negativo.
"""
from time import sleep
contador = 0
contador2 = 0
continuar_o_programa = True
while continuar_o_programa == True:
contador+=1
numero_digitado = int(input(f'Digite o {contador}° número para fazer sua tabuada(digite um valor negativo para parar): '))
if numero_digitado >=0:
contador2+=1
print('=-='*30)
while contador2<=10:
print(f'{numero_digitado:2} x {contador2:2} = {numero_digitado*contador2:2}')
contador2+=1
sleep(1)
contador2 = 0
print('=-='*30)
else:
print('Finalizando o programa...')
sleep(1)
break
| false |
bba25468bfcaf2099c340f3885696923b26e306e | lvfds/Curso_Python3 | /mundo_1/desafios/desafio_023.py | 870 | 4.15625 | 4 | """
Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos digitos separados.
Ex:
Digite um número: 1834
unidade: 4
dezena: 3
centena: 8
milhar: 1
"""
numero_digitado = input('Digite um número: ')
if len(numero_digitado) == 1:
print(f'Unidade: {numero_digitado[0]}')
else:
if len(numero_digitado) == 2:
print(f'Unidade: {numero_digitado[1]}')
print(f'Dezena: {numero_digitado[0]}')
elif len(numero_digitado) == 3:
print(f'Unidade: {numero_digitado[2]}')
print(f'Dezena: {numero_digitado[1]}')
print(f'Centena: {numero_digitado[0]}')
elif len(numero_digitado) == 4:
print(f'Unidade: {numero_digitado[3]}')
print(f'Dezena: {numero_digitado[2]}')
print(f'Centena: {numero_digitado[1]}')
print(f'Milhar: {numero_digitado[0]}')
| false |
4014223c1f55c29d631b5918b851e2e2769d61e2 | lvfds/Curso_Python3 | /mundo_2/desafio_072.py | 687 | 4.375 | 4 | """
Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte.
Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.
"""
numeros_por_extenso = ('Zero','Um','Dois','Três','Quatro','Cinco','Seis','Sete','Oito','Nove','Dez','Onze','Doze','Treze','Catorze','Quinze','Dezesseis','Dezessete','Dezoito','Dezenove','Vinte')
numero_digitado = int(input('Digite um número entre 0 e 20: '))
while numero_digitado < 0 or numero_digitado > 20:
numero_digitado = int(input('Tente novamente. Digite um número entre 0 e 20: '))
print(f'Você digitou o número {numeros_por_extenso[numero_digitado]}.') | false |
949f58bd10b818923c78e03ae6e044170e5c0d46 | lvfds/Curso_Python3 | /mundo_1/desafios/desafio_028.py | 632 | 4.28125 | 4 | """
Escreva um programa que faça o computador 'Pensar' em um número inteiro entre 0 e 5
e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
"""
from random import randint
numero_gerado_aleatoriamente = randint(0,5)
numero_digitado_pelo_usuario = int(input('Adivinhe qual número estou pensando, uma dica: é entre 0 e 5! '))
if numero_digitado_pelo_usuario == numero_gerado_aleatoriamente:
print(f'VOCÊ ACERTOU! O número que estava pensando era mesmo o {numero_gerado_aleatoriamente}!')
else:
print(f'Você errou! O número que pensei era {numero_gerado_aleatoriamente}')
| false |
ba551eddf5a18a7044801bb7907df01c3fe40220 | lvfds/Curso_Python3 | /mundo_1/desafios/desafio_004.py | 736 | 4.1875 | 4 | # Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
algo_digitado_pelo_usuario = input('Digite algo: ')
print(f'O tipo primitivo desse valor é {type(algo_digitado_pelo_usuario)}')
print(f'Só tem espaços? {algo_digitado_pelo_usuario.isspace()}')
print(f'É um número? {algo_digitado_pelo_usuario.isnumeric()}')
print(f'É alfabético? {algo_digitado_pelo_usuario.isalpha()}')
print(f'É alfanúmerico? {algo_digitado_pelo_usuario.isalnum()}')
print(f'Está em maísculas? {algo_digitado_pelo_usuario.isupper()}')
print(f'Está em minúsculas? {algo_digitado_pelo_usuario.islower()}')
print(f'Está capitalizada? {algo_digitado_pelo_usuario.istitle()}') | false |
5a00cec088a18c1dcf20908b1817e5cd08e6f189 | raferti/code_war | /recover_secret_string_from_random_triplets.py | 1,977 | 4.125 | 4 | """
There is a secret string which is unknown to you. Given a collection of
random triplets from the string, recover the original string.
A triplet here is defined as a sequence of three letters such that each
letter occurs somewhere before the next in the given string. "whi" is a
triplet for the string "whatisup".
As a simplification, you may assume that no letter occurs more than once
in the secret string.
You can assume nothing about the triplets given to you other than that
they are valid triplets and that they contain sufficient information to
deduce the original string. In particular, this means that the secret
string will never contain letters that do not occur in one of
the triplets given to you.
"""
# Solution 1
def merge_to_one_list(triplets):
one_list = []
for line in triplets:
one_list += line
return list(set(one_list))
def swap(a, b, secret_list):
index_a = secret_list.index(a)
index_b = secret_list.index(b)
secret_list[index_a], secret_list[index_b] = b, a
return secret_list
def recoverSecret(triplets):
secret = merge_to_one_list(triplets)
flag = True
while flag:
flag = False
for line in triplets:
if secret.index(line[0]) > secret.index(line[1]):
secret = swap(line[1], line[0], secret)
flag = True
if secret.index(line[0]) > secret.index(line[2]):
secret = swap(line[2], line[0], secret)
flag = True
if secret.index(line[1]) > secret.index(line[2]):
secret = swap(line[2], line[1], secret)
flag = True
return ''.join(secret)
# Solution 2
def recoverSecret_two(triplets):
r = list(set([i for l in triplets for i in l]))
for l in triplets:
fix(r, l[1], l[2])
fix(r, l[0], l[1])
return ''.join(r)
def fix(l, a, b):
if l.index(a) > l.index(b):
l.remove(a)
l.insert(l.index(b), a)
| true |
e0fc6db597a2366baa0fd1f924ef2434e32f1410 | raferti/code_war | /calculator.py | 1,395 | 4.40625 | 4 | """
Create a simple calculator that given a string of operators (), +, -, *, /
and numbers separated by spaces returns the value of that expression
Example:
Calculator().evaluate("2 / 2 + 3 * 4 - 6") # => 7
Remember about the order of operations! Multiplications and divisions have
a higher priority and should be performed left-to-right. Additions and
subtractions have a lower priority and should also be performed left-to-right.
calc = Calculator()
print(calc.evaluate('2 + 3 * 4 / 3 - 6 / 3 * 3 + 8'))
"""
class Calculator(object):
def update_list(self, source, opr):
swith = {
'/': lambda x, y: x / y,
'*': lambda x, y: x * y,
'-': lambda x, y: x - y,
'+': lambda x, y: x + y
}
ss_copy = source[:]
idx = source.index(opr)
a = float(ss_copy.pop(idx - 1))
b = float(ss_copy.pop(idx))
res = swith[opr](a, b)
ss_copy.remove(opr)
ss_copy.insert(idx - 1, res)
return ss_copy
def evaluate(self, string):
ss = string.split()
while len(ss) > 1:
for sign in ss:
if (sign == '/') or (sign == '*'):
ss = self.update_list(ss, sign)
for sign in ss:
if (sign == '+') or (sign == '-'):
ss = self.update_list(ss, sign)
return float(ss[0])
| true |
5df0a3355c0c64bddb283a5908f95b6f304eaea0 | AfanasAbigor/Python_Basic | /GUI_Turtle_Race.py | 1,412 | 4.1875 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width=500, height=500) #Set height & width of Screen
screen.bgcolor("black") #change BackGround Color
line = Turtle("turtle")
line.goto(250, 250)
line.color("white")
line.right(90)
line.forward(500)
user_bet = screen.textinput(title="Make Your Bet From Rainbow Color!!!",
prompt="Which Turtle Will Win The Race? Enter A Color!").lower()
colors = ["purple", "blue", "skyblue", "green", "yellow", "orange", "red"]
list_y = [-70, -40, -10, 20, 50, 80, 110] #y coordinate distance
all_turtle = []
is_race_on = False
for turtle_index in range(0, 7):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[turtle_index])
new_turtle.penup()
new_turtle.goto(x=-230, y=list_y[turtle_index])
all_turtle.append(new_turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() > 230: #250-20 = size of turtle is 20 pixel.
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You've Won!\n{winning_color} is The Winner!!!")
else:
print(f"You Have Loss.\nThe Winning Turtle is {winning_color}.")
random_distance = random.randint(0, 10)
turtle.forward(random_distance)
screen.exitonclick()
| true |
d30eecb90b4125692e7f4512d822ac129e17855f | VilarPedro/Scripts-Python | /exercicios/Ex004.py | 2,641 | 4.46875 | 4 | '''
04) Faça um programa que leia algo pelo teclado e mostre na tela o seu
tipo primitivo e todas as informações possiveis sobre ela.
'''
# n = 'pedro'
# print()
var = input('Digite algo: ')
print('O que você digitou pode ser um numero:',var.isnumeric())
print('O que você digitou pode ser uma string:',var.isalpha())
# print('O que você digitou pode ser um numero:',var.isnumeric())
# print('O que você digitou pode ser um numero:',var.isnumeric())
# print('O que você digitou pode ser um numero:',var.is())
# n = 'pedro'
# print(n.is)
# __ Solução do guanabara
# a função input sempre irá retornar um tipo str.
a = input('Digite algo: ')
print('O tipo primitivo desse valor é ', type(a))
# Verifica se tem somente espaços
print('Só tem espaços? ', a.isspace())
# verificar se só é numerico
print('é um numero? ', a.isnumeric())
# verificar se só é alfabético
print('é alfabético? ', a.isalpha())
print('é alfanumérico? ', a.isalnum())
print('está em maiúsculo? ', a.isupper())
print('está em minúscula? ', a.islower())
print('está capitalizada? ', a.istitle())
# isalnum
# isalpha
# isnumeric
# isspace
# isprintable
# isdecimal
# istitle
# islower
# isupper
# isdigit
# Todo obejeto tem caracteristicas e possui funcionalidades, atributos e metodos.
# Todos os métodos da string
'''
Método Parâmetros Descrição
upper nenhum Retorna um string todo em maiúsculas
lower nenhum Retorna um string todo em minúsculas
capitalize nenhum Retorna um string com o primeiro caractere em maiúscula, e o resto em minúsculas
strip nenhum Retorna um string removendo caracteres em branco do início e do fim
lstrip nenhum Retorna um string removendo caracteres em brando do início
rstrip nenhum Retorna um string removendo caracteres em brando do fim
count item Retorna o número de ocorrências de item
replace old, new Substitui todas as ocorrências do substring old por new
center largura Retorna um string centrado em um campo de tamanho largura
ljust largura Retorna um string justificado à esquerda em um campo de tamanho largura
rjust largura Retorna um string justificado à direita em um campo de tamanho largura
find item Retorna o índice mais à esquerda onde o substring item é encontrado
rfind item Retorna o índice mais à direita onde o substring item é encontrado
index item Como find, mas causa um erro em tempo de execução caso item não seja encontrado
rindex item Como rfind, mas causa um erro em tempo de execução caso item não seja encontrado
'''
| false |
b9c93ccdc24fee371cb9a0e2da8de6c0c71bdab8 | mateuspadua/design-patterns | /creational/singleton/refactoring-guru.py | 1,375 | 4.3125 | 4 | from typing import Optional
class Singleton:
"""
The Singleton class defines the `getInstance` method that lets clients
access the unique singleton instance.
"""
_instance: Optional = None
def __init__(self) -> None:
if Singleton._instance is not None:
raise ReferenceError("Cannot instantiate a singleton class.")
else:
Singleton._instance = self
@staticmethod
def get_instance() -> Singleton:
"""
The static method that controls the access to the singleton instance.
This implementation let you subclass the Singleton class while
keeping just one instance of each subclass around.
"""
if not Singleton._instance:
Singleton()
return Singleton._instance
def some_business_logic(self):
"""
Finally, any singleton should define some business logic, which can
be executed on its instance.
"""
pass
class Demo:
# The client code.
def run(self) -> None:
s1 = Singleton.get_instance()
s2 = Singleton.get_instance()
if id(s1) == id(s2):
print("Singleton works, both variables contain the same instance.")
else:
print("Singleton failed, variables contain different instances.")
demo: Demo = Demo()
demo.run() | true |
2e27d73c47bd768f5c78a156a4db813ffc2a2fbd | mateuspadua/design-patterns | /advanced_python_topics/inheritance.py | 1,028 | 4.25 | 4 |
class Pet:
""" Base class for all pets """
def __init__(self, name, species):
self.name = name
self.species = species
def get_name(self):
return self.name
def get_species(self):
return self.species
def __str__(self):
return '{} is a {}'.format(self.name, self.species)
class Dog(Pet):
def __init__(self, name, chases_cats):
"""
This is a overloading
Same method with custom parameters
"""
super().__init__(name, 'Dog')
self.chases_cats = chases_cats
def chases_cats(self):
return self.chases_cats
def __str__(self):
"""
This is a override
Same method and same attributes
"""
additional_info = ''
if self.chases_cats:
additional_info = ' who chases cats'
return super().__str__() + additional_info
p = Pet('Polly', 'Parrot')
p.__str__()
Pet.__subclasses__()
d = Dog('Fred', True)
d.__str__()
Dog.__bases__ | true |
9fce218f362efcd12371809d4ace99df88e07e2e | mateuspadua/design-patterns | /creational/abstract_factory/udemy.py | 1,732 | 4.1875 | 4 | """
Provide an interface for creating
families of related objects without
specifying their concrete classes.
"""
# abstract classes (interfaces)
class Shape2DInterface:
def draw(self):
raise NotImplementedError()
class Shape3DInterface:
def build(self):
raise NotImplementedError()
# concrete 2D classes
class Circle(Shape2DInterface):
def draw(self):
print('Circle.draw')
class Square(Shape2DInterface):
def draw(self):
print('Square.draw')
# concrete 3D classes
class Sphere(Shape3DInterface):
def build(self):
print('Sphere.build')
class Cube(Shape3DInterface):
def build(self):
print('Cube.build')
# abstract shape factory
class ShapeFactoryInterface:
def get_shape(sides):
raise NotImplementedError()
# concrete shape factories
class Shape2DFactory(ShapeFactoryInterface):
@staticmethod
def get_shape(sides):
if sides == 1:
return Circle()
elif sides == 4:
return Square()
raise Exception('Bad 2D shape creation: shape not defined for ' + sides + ' sides')
class Shape3DFactory(ShapeFactoryInterface):
@staticmethod
def get_shape(sides):
""" here, sides refers to the numbers of faces """
if sides == 1:
return Sphere()
elif sides == 6:
return Cube()
raise Exception('Bad 3D shape creation: shape not defined for ' + sides + ' faces')
# run
shape_2 = Shape2DFactory.get_shape(1)
shape_2.draw() # circle
shape_2 = Shape2DFactory.get_shape(4)
shape_2.draw() # square
shape_3 = Shape3DFactory.get_shape(1)
shape_3.build() # sphere
shape_3 = Shape3DFactory.get_shape(6)
shape_3.build() # cube
| true |
49188346ad80651c8f6072b6e7639f5646bb38ab | paulosrlj/PythonCourse | /Módulo 1 - Python Básico/Aula20 - Listas/aula020.py | 1,144 | 4.125 | 4 | # Listas
'''
append, insert, pop, del, clear, extend
append -> adiciona um elemento
insert -> adiciona um elemento em uma posição
pop -> retira da ultima posição
del -> deleta das posições especificadas
extend -> extende uma lista com outra
'''
# 0 1 2 3 4
lista = ['A', 'B', 'C', 'D', 'E']
# - 5 4 3 2 1
# print(lista[::-1]) //Imprime ao contrário
l1 = [1, 2, 3]
l2 = [4, 5, 6]
# l3 = l1 + l2
l1.extend(l2)
print(l1)
l2.append('A')
print(l2)
l2.insert(0, 'Banana')
print(l2)
l2.pop()
print(l2)
del(l2[-1:])
print(l2)
# Exemplo, gerar números de 0 a 100, multiplos de 5
l3 = list(range(0, 101, 5))
print(l3)
l4 = ['String', True, 10, 25.75]
for valor in l4:
print(f'O valor {valor} é do tipo {type(valor)}')
secreto = 'perfume'
digitadas = []
while True:
letra = input('Digite uma letra: ')
if len(letra) > 1:
print('Isso não vale, digite apenas uma letra.')
continue
digitadas.append(letra)
if letra in secreto:
print('A letra existe na palavra')
else:
print('A letra não existe na palavra secreta')
digitadas.pop()
| false |
e0f66b5ac2b3136a38a93187e8a4732d83f744f6 | apurva13/assignment-2 | /answer3.py | 249 | 4.3125 | 4 | #Take the input of 3 variables x, y and z . Print their values on screen.
x=int(input('enter value of x:'))
y=int(input('enter value of y:'))
z=int(input('enter value of z:'))
print ('Value of x:',x)
print ('Value of y:',y)
print ('Value of z:',z)
| true |
5f8cd3f80f15bae62a50d6989c530d06e3453f32 | litvinovserge/WebAcademy | /HomeWork_06/AssertTests/assert_Task_09.py | 665 | 4.34375 | 4 | """
Из одномерного списка удалить все повторяющиеся элементы (дубликаты) так, чтобы каждое значение встречалось в списке
только один раз.
"""
def list_modifier(some_list):
new_list = []
for i in range(len(some_list)):
for j in range(i):
if some_list[j] == some_list[i]:
some_list[j] = None
for i in range(len(some_list)):
if some_list[i] == 0 or some_list[i]:
new_list.append(some_list[i])
return new_list
if __name__ == '__main__':
assert list_modifier([1, 1, 2]) == [1, 2] | false |
31e5779cbd41da74ab9a0cb0b9dc07a97290712f | litvinovserge/WebAcademy | /HomeWork_07/HomeTask_01.py | 1,250 | 4.28125 | 4 | """
Создать класс автомобиль, который содержит информацию о автомобилях
Описать метод __str__
***
Пример
>> car1 = Car(‘Audi’, ‘Red’, ‘1999’, ‘$12000’)
>>print(car1)
name: Audi
color: Red
year: 1999
price: $12000
"""
class Car:
def __init__(self, model=None, color=None, year=None, price=None):
self.model = model
self.color = color
self.year = year
self.price = price
def __str__(self):
car_info = [
'model: ' + self.model,
'color: ' + self.color,
'year: ' + str(self.year),
'price: ' + str(self.price),
]
return '\n'.join(car_info)
def showinfo(self):
print(self)
if __name__ == '__main__':
Audi = Car('Audi', 'Black', '2018', '35 000$')
VW = Car('VW', 'Grey', '2015', '15 000$')
Opel = Car('Opel', 'Yellow', '2013', '13 500$')
print('***Реализация через строковое представление объекта (метод __str__)***', Audi, sep='\n')
print('***Реализация через метод класса***'), VW.showinfo()
| false |
84acfee70bb3704b36d5b25451362ffee2067c54 | litvinovserge/WebAcademy | /HomeWork_06/Task_16.py | 841 | 4.125 | 4 | """
Программа переводчик из соленого языка.
ПРИМЕР
Посокесемосон -> Покемон
"""
vowels = ['а', 'о', 'и', 'й', 'е', 'ё', 'э', 'ы', 'у', 'ю', 'я']
test_data = 'Приcивеcет, Cаcальсаcа, Посокесемосон!'
def anti_salty_transform(some_phrase):
some_phrase = list(some_phrase)
for i in range(len(some_phrase)):
for j in range(len(vowels)):
if some_phrase[i].lower() == vowels[j]:
some_phrase[i + 1] = ''
some_phrase[i + 2] = ''
return ''.join(some_phrase)
if __name__ == '__main__':
user_phrase = input('Введите Вашу солёную фразу или слово: ')
if not user_phrase:
user_phrase = test_data
print(anti_salty_transform(user_phrase))
| false |
f3615592e3016700b30e2d4d8ba6a540c677fecd | litvinovserge/WebAcademy | /HomeWork_06/AssertTests/assert_Task_11.py | 497 | 4.15625 | 4 | """
Дан список значений. Превратить список в словарь где ключами служат элементы списка,
а значениями квадраты этих элементов.
[1,2,3] -> {1:1, 2:4, 3:9}
"""
def dict_2_list(some_list):
my_dict = {}
for i in range(len(some_list)):
my_dict[some_list[i]] = some_list[i] ** 2
return my_dict
if __name__ == '__main__':
assert dict_2_list([1, 2, 3]) == {1: 1, 2: 4, 3: 9} | false |
0a059e009e378c9a8354b99674d8ff7ba7ec6d92 | jonggukim/Python-for-Trading | /About Python/about condition.py | 541 | 4.15625 | 4 | ###조건문
# if :
# if and else
if True:
print('this is true results')
# 조건문:2
# if
input = 11
real = 11
if real == input:
print("hello if conditional statement programming")
# else
if real != input:
print("who are you")
'''
more simple code below
else:
print("who are you")
'''
#조건문:3
# 여러가지 조건에 대하여 동작하는 code.
nput = 11
real_user1 = 11
real_user2 = 22
if real_user1 == input:
print("Hi user1")
elif real_user2 == input:
print("Hi user2")
else:
print("who are you")
| false |
966665af55225f40fdd4da19c28dd883a43f62ff | davidknoppers/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 367 | 4.1875 | 4 | #!/usr/bin/python3
"""
One function in this module
append_write opens a file and appends some text to it
"""
def append_write(filename="", text=""):
"""
open file
put some text at the end of it
close that file
"""
with open(filename, mode='a', encoding="utf-8") as myFile:
chars_written = myFile.write(text)
return chars_written
| true |
b34422e86b7dab5bb5166bc8f2db81eae755310f | davidknoppers/holbertonschool-higher_level_programming | /0x06-python-test_driven_development/5-text_indentation.py | 563 | 4.21875 | 4 | #!/usr/bin/python3
"""
text_indentation - inserts newline into a text
Requires a str input, otherwise raises errors
Prints the result, no return value
"""
def text_indentation(text):
"""
Adds newlines to a string based on sep, and prints it
"""
if text is None or not isinstance(text, str) or len(text) < 0:
raise TypeError('text must be a string')
text = text.replace('.', '.\n\n')
text = text.replace('?', '?\n\n')
text = text.replace(':', ':\n\n')
print('\n'.join([line.strip() for line in text.split('\n')]), end="")
| true |
2ffd661c6dd804ab70294c05204bc7a5fe835a1b | davidknoppers/holbertonschool-higher_level_programming | /0x07-python-classes/100-singly_linked_list.py | 2,312 | 4.125 | 4 | #!/usr/bin/python3
"""
Implementation of a basic singly linked list in Python
Sorted lowest to highest by node value
Offers basic print function
"""
class Node(object):
"""
creates node with next set to None as default
"""
def __init__(self, data, next_node=None):
if type(data) is not int or isinstance(data, bool):
raise TypeError('data must be an integer')
self.__data = data
self.__next_node = next_node
@property
def data(self):
"""
getter for data
"""
return (self.__data)
@data.setter
def data(self, value):
"""
setter for data
"""
if not isinstance(value, int) or isinstance(value, bool):
raise TypeError('data must be an integer')
self.__data = value
@property
def next_node(self):
"""
getter for node
"""
return self.__next_node
@next_node.setter
def next_node(self, value):
"""
setter for node
"""
if value is not None and type(value) is not Node:
raise TypeError('next must be a Node object')
self.__next_node = value
class SinglyLinkedList(object):
"""
Singly linked list
Uses node class
Contains a print function and sorts by int value
"""
def __init__(self):
"""
init
"""
self.__head = None
def sorted_insert(self, value):
"""
inserts by int value
"""
if not self.__head:
self.__head = Node(value, None)
else:
current = self.__head
prev = None
while current and value > current.data:
prev = current
current = current.next_node
if not current:
prev.next_node = Node(value)
elif current == self.__head:
self.__head = Node(value, current)
else:
prev.next_node = Node(value, current)
def __str__(self):
"""
formats list for output
"""
result = ""
temp = self.__head
while temp:
result += str(temp.data)
temp = temp.next_node
if temp:
result += '\n'
return result
| true |
ed88d540806403c4065e0c86ec650b49d81f01cc | kristocode/30-Days-Of-Python | /12_Day_Modules/day12_level3.py | 884 | 4.15625 | 4 | ## 💻 Exercises: Day 12
### Exercises: Level 3
import random
import string
#1. Call your function shuffle_list, it takes a list as a parameter and it returns a shuffled list
def shuffle_list(lst):
return random.sample(lst, k=len(lst)) # unique items
#return random.choices(lst, k=len(lst)) # repeated items
original = [2, 3, 4, 6, 7]
print('original : ',original, ' - random : ',shuffle_list(original))
original = [2, '33', 4, 6, 7, 'blue', 12.3]
print('original : ',original, ' - random : ',shuffle_list(original), '\n')
#2. Write a function which returns an array of seven random numbers in a range of 0-9.
# All the numbers must be unique.
def seven_unique_random_number():
return random.sample(range(10), 7)
print(seven_unique_random_number())
print(seven_unique_random_number())
print(seven_unique_random_number())
print(seven_unique_random_number())
| true |
3f2aaf74de320538b1f37de59c0166a487ded404 | kristocode/30-Days-Of-Python | /06_Day_Tuples/day6_level1.py | 743 | 4.59375 | 5 | ## 💻 Exercises: Day 6
### Exercises: Level 1
# 1. Create an empty tuple
my_tuple = tuple()
# 2. Create a tuple containing names of your sisters and your brothers (imaginary siblings are fine)
sisters = ('Janis Joplin', 'Amy Winehouse')
brothers = ('Brian Jones', 'Jimi Hendrix', 'Jim Morrison', 'Kurt Cobain')
# 3. Join brothers and sisters tuples and assign it to siblings
club_27 = brothers + sisters
# 4. How many siblings do you have?
print(f'I have {len(club_27)} siblings\n')
# 5. Modify the siblings tuple and add the name of your father and mother and assign it to family_members
family_members = list(club_27)
family_members.append('father_name')
family_members.append('mather_name')
club_27 = tuple(family_members)
print(f'Added father and mather : {club_27}\n') | true |
469962a7100b3671df69de5b5897d0a25766b0d5 | kristocode/30-Days-Of-Python | /09_Day_Conditionals/day9_level1.py | 1,750 | 4.40625 | 4 | ## 💻 Exercises: Day 9
### Exercises: Level 1
# 1. Get user input using input(“Enter your age: ”). If user is 18 or older, give feedback:
# You are old enough to drive. If below 18 give feedback to wait for the missing amount of years. Output:
'''sh
Enter your age: 30
You are old enough to learn to drive.
Output:
Enter your age: 15
You need 3 more years to learn to drive.
'''
age = int(input('Enter your age: '))
if(age >= 18):
print('You are old enough to learn to drive.\n')
else:
print(f'You need {18-age} more years to learn to drive.\n')
# 2. Compare the values of my_age and your_age using if … else.
# Who is older (me or you)? Use input(“Enter your age: ”) to get the age as input.
# You can use a nested condition to print 'year' for 1 year difference in age,
# 'years' for bigger differences, and a custom text if my_age = your_age. Output:
'''sh
Enter your age: 30
You are 5 years older than me.
'''
age = int(input('Enter your age: '))
me = 25
if(age > me):
rest = age-me
print("You are",rest,"year"+("s" if(rest>1) else ""),"older than me.\n")
elif (age == me):
print("You are the same age as me\n")
else:
rest = me-age
print("I am",rest,"year"+("s" if(rest>1) else ""),"older than you.\n")
# 3. Get two numbers from the user using input prompt.
# If a is greater than b return a is greater than b,
# if a is less b return a is smaller than b, else a is equal to b. Output:
'''sh
Enter number one: 4
Enter number two: 3
4 is greater than 3
'''
one = int(input('Enter number one: '))
two = int(input('Enter number two: '))
if(one>two):
print(f"{one} is greater than {two}")
elif (one<two):
print(f"{one} is smaller than {two}")
else:
print(f'{one} is equal to {two}') | true |
70e08680dd30b42b73e81517084f828c03f36fce | huilizhou/Leetcode-pyhton | /algorithms/201-300/225.implement-stack-using-queues.py | 2,080 | 4.28125 | 4 | # 用队列实现栈
# class MyStack:
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.l = []
# def push(self, x):
# """
# Push element x onto stack.
# :type x: int
# :rtype: void
# """
# self.l.append(x)
# def pop(self):
# """
# Removes the element on top of the stack and returns that element.
# :rtype: int
# """
# return self.l.pop()
# def top(self):
# """
# Get the top element.
# :rtype: int
# """
# return self.l[-1]
# def empty(self):
# """
# Returns whether the stack is empty.
# :rtype: bool
# """
# return self.l == []
# # Your MyStack object will be instantiated and called as such:
# # obj = MyStack()
# # obj.push(x)
# # param_2 = obj.pop()
# # param_3 = obj.top()
# # param_4 = obj.empty()
# 人家的写法
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = []
self.stack2 = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
if not self.stack1:
self.stack1.append(x)
while self.stack2:
self.stack1.append(self.stack2.pop(0))
else:
self.stack2.append(x)
while self.stack1:
self.stack2.append(self.stack1.pop(0))
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
return self.stack1.pop(0) if self.stack1 else self.stack2.pop(0)
def top(self):
"""
Get the top element.
:rtype: int
"""
return self.stack1[0] if self.stack1 else self.stack2[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.stack1 and not self.stack2
| true |
9f29346dce506d85d142a63494d270a88db07459 | sloth143chunk/Election_Analysis | /Assisngments/F_String.py | 1,559 | 4.15625 | 4 | # Original concatenation
# my_votes = int(input("How many votes did you get in the election? "))
# total_votes = int(input("What is the total votes in the election? "))
# percentage_votes = (my_votes / total_votes) * 100
# print("I received " + str(percentage_votes)+"% of the total votes.")
# F-String Printing
# my_votes = int(input("How many votes did you get in the election? "))
# total_votes = int(input("What is the total votes in the election? "))
# print(f"I received {my_votes / total_votes * 100}% of the total votes.")
# Original Concatenation
counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222}
for county, voters in counties_dict.items():
print(county + " county has " + str(voters) + " registered voters.")
# F-String Printing
for county, voters in counties_dict.items():
print(f"{county} county has {voters} registered voters.")
# Multiline F-Strings
candidate_votes = int(input("How many votes did the candidate get in the election? "))
total_votes = int(input("What is the total number of votes in the election? "))
message_to_candidate = (
f"You received {candidate_votes} number of votes. "
f"The total number of votes in the election was {total_votes}. "
f"You received {candidate_votes / total_votes * 100:.2f}% of the total votes.")
print(message_to_candidate)
# Formate floating-point decimals
# General format, width = number of characters and percision = .2f or however many decimal points
# f'{value:{width}.{precision}}'
# Comma for thousands
# f'{value:{width},.{precision}}' | true |
8a6fdcb1907629d142b55fe8759f4d8b266e71f8 | yashsinghal07/Music-Player | /Project_gui/guidemo.py | 1,595 | 4.28125 | 4 | import tkinter
tw=tkinter.Tk()
#tw is refference of tkinter class
#title() and mainloop() are instance members of tkinter class hence refference tw can call them
#title() - changes the title of root window
tw.title("My Gui App")
#next 2 lines changes the logo on the screen
img=tkinter.PhotoImage(file="E:/project related/NBA web page/lebron-james-wallpapers.png")
tw.iconphoto(tw,img)
#to the the size of the screen
#geometry("width_x_height")
tw.geometry("600x400")
#to set the position of screen
#geometry("width_x_height+distance_from_left_end+distance_from_top")
tw.geometry("600x400+350+150")
#to make the window appear on the center of the screen...we'll use the maths as screen size as 50% of total size and leaving 25%on all the sides
sw=tw.winfo_screenwidth()
sh=tw.winfo_screenheight()
ww=sw//2
wh=sh//2
x=sw//4
y=sh//4
print(ww)
print(wh)
tw.geometry(f"{ww}x{wh}+{x}+{y}")#f string is used as we need to convert variables to string...variables are written within {} braces
tw.resizable(False,False)
#adding widgets to the screen
lbl1=tkinter.Label(tw,text="Be Cool ... Be Dude")
lbl2=tkinter.Label(tw,text="python rocks!...")
#pack() is necessary to make label appear on the screen
#the order in which we pack resultes in the same order in whick they appear on screen irrespective of order of creating them(lbl1 or lbl2)
lbl1.pack()
lbl2.pack()
tw.mainloop()
#program pauses after mainloop(). the program will move forward only when we'll close the window.
#hence in gui application we will always use mainloop() in the end to display the screen.
| true |
ab84718b1454e7e99875966a6ee98e0cd3ba7cf2 | theTransponster/Data-Science | /Statistics/Interquartile.py | 1,990 | 4.1875 | 4 | #Basic code to find the interquartile range in python without using libraries
#The objective of this code is to understand the concept of interquartile range from scratch
#Interquartil: (Q3-Q1)
#Reads from STDIN, prints on STDOUT
n = int(input()) #number of elements of the array
numbers = list(map(int, input().split('Enter the numbers on a single line separated by spaces: '))) #elements on the vector
frequency = list(map(int, input().split('Enter the frequency of each number (in the same order) separated by spaces: ')))
arr = []
#Make a vector repeating each number according to the frequencies entered
for x,y in zip(numbers,frequency):
for i in range(0,y):
arr.append(x)
arr = sorted(arr)
#print(arr)
def lower_half (numbers):
low=[]
n= len(numbers)
if n%2 == 0:
low.append(numbers[0:int(n/2)])
else:
low.append(numbers[0:int(n/2)])
return low
def upper_half(numbers):
up=[]
n = len(numbers)
if n%2 == 0:
up.append(numbers[int(n/2):n])
else:
up.append(numbers[int(n/2)+1:n])
return up
def median(lista):
median1 = 0
n1 = 0
n2 = 0
nn = len(lista)
if nn%2 == 0:
n1 = lista[int(nn/2)-1]
n2 = lista[int(nn/2)]
median1 = ((n1 + n2)/2)
else:
n1 = lista[int(nn/2)]
median1 = n1
return median1
L = lower_half(arr)
U = upper_half(arr)
Q1 = median(L[0])
Q2 = median(arr)
Q3 = median(U[0])
#print(Q1)
#print(Q2)
#print(Q3)
print('{:.1f}'.format(Q3-Q1))
| true |
af3f83953f214f2e57d6b624e97078ba98a55194 | thirdeye18/mycode | /iftest/condition02.py | 504 | 4.125 | 4 | #!/usr/bin/env python3
## Program checks the hostname against the expected value
hostname = input("What value should we set for hostname?")
## Notice how the next line has changed
## here we use the str.lower() method to return a lowercase string
if hostname.lower() == "mtg":
print("The hostname matches the expected configuration(mtg)")
else:
print("The hostname does not match the expected configuration")
# Final message for exiting program, always prints
print("The program is exiting.")
| true |
cc9b05fc91cad733e6ff451665f286686fbff3a4 | chaconcarlos/udacity-data-structures-algorithms | /1-introduction/Task0.py | 1,268 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of texts and what is the last record of calls?
Print messages:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
first_text_message_format = "First record of texts, {0} texts {1} at time {2}"
last_call_message_format = "Last record of calls, {0} calls {1} at time {2}, lasting {3} seconds"
first_text = texts[0]
first_text_message = first_text_message_format.format(first_text[0], first_text[1], first_text[2])
last_call = calls[len(calls) - 1]
last_call_message = last_call_message_format.format(last_call[0], last_call[1], last_call[2], last_call[3])
print(first_text_message)
print(last_call_message)
# The worst case of my implementation for this task is: O(1). Both lookup operations are constant, as the get item operation
# for a list in Python is O(1) | true |
4963b5ae16ba641584b71e505b0e62173883b411 | vinhloc30796/calculate_gap_year | /calculate.py | 739 | 4.28125 | 4 | def is_leap_year(year):
"""
Check if input `year` is a leap year
Input:
- year (int)
Output:
- leap (boolean): True if is leap year, False otherwise
"""
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
return False
def next_five_leap(year):
"""Return the next five leap years after input `year`
Input:
- year (int)
Output:
- result (list of int): list of 5 years that are leap years
"""
result = {}
count = 0
while count < 5:
year += 1
if is_leap_year(year):
result[year] = True
count += 1
if year % 100 == 0 and not is_leap_year(year):
result[year] = False
return result
| false |
ec183b0b74cbc6563b066d89c2008bea6a550a0a | zaarabuy0950/assignment-3 | /assign4.py | 477 | 4.28125 | 4 | #4. Create a list. Append the names of your colleagues and friends to it.
#Has the id of the list changed? Sort the list. What is the first item onthe list?
# What is the second item on the list?
list = []
print(id(list))
list.append('zanda')
list.append('yabin')
list.append('kendra')
print(list)
print(id(list))
print(f"Id list before:{id(list)} and list id after:{id(list)} are same")
a = sorted(list)
print(a)
print(f"first item: {a[0]}")
print(f"second item: {a[1]}")
| true |
0445950df9813809d215cc6f1ce154fdb274c79d | zaarabuy0950/assignment-3 | /assign12.py | 352 | 4.25 | 4 | #12. Create a function, is_palindrome, to determine if a supplied word is the same if the letters are reversed.
asd = input("enter a string:")
qwe = asd[::-1]
print(qwe)
def is_palindrome(asd, qwe):
if asd == qwe:
return f"The Word are Same string"
else:
return f"The word are not same string"
print(is_palindrome(asd,qwe))
| true |
4804982df745b4072c909b5e153812cb558f53b5 | satheeshkumars/my_chapter_6_solution_gaddis_book_python | /exception_handling.py | 600 | 4.34375 | 4 | #use the numbers.txt file to practise this piece of code
def main():
try:
open_numbers = open('numbers.txt', 'r')
except IOError:
print('Unable to open file and read data!')
accumulator = 0
counter = 0
for number in open_numbers:
number = number[:-1]
try:
accumulator += int(number)
except ValueError:
print('Unable to convert item to number!')
counter += 1
average = accumulator / counter
print('The average of all the numbers stored in the numbers.txt file is', average)
main() | true |
e0bbe15a2e57c4d595cc80fee99450361947c23c | harkred/High-School-Programs | /program12.py | 363 | 4.21875 | 4 | #To convert binary no to decimal no
def binary_to_decimal(num):
num = num[::-1]
decimal = 0
for place in range(len(num)):
digit = num[place]
two_expo = 2 ** place
adduct = int(digit) * two_expo
decimal += adduct
return decimal
#__main__
if __name__ == '__main__':
num = '101'
print(binary_to_decimal(num))
| false |
1ff0fe784d7302ca1f5fb1ba4996309ebd84017e | Shivansh-Uppal/python-coursera | /file2.py | 748 | 4.15625 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
#X-DSPAM-Confidence: 0.8475
#Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
fname = input("Enter file name: ")
fh = open(fname)
count = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
count = count + 1
total = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
line = float(line[21:])
total = line + total
average = total/ count
print("Average spam confidence:",average)
| true |
ea67f5ba2f78d7bfb1007cddbea6ebaa801dea92 | Rockyzsu/StudyRepo | /python/basic/var.py | 464 | 4.1875 | 4 | #/usr/bin/python3.5
#coding: utf-8
#一次赋 多值
v = ('a', 'b', 'e')
x, y, z = v
print(x+', '+y+', '+z)
'''
(1) v 是一个三元素的 tuple,并且 (x, y, z) 是一个三变量的 tuple。将一个 tuple
赋值给另一个 tuple,会按顺序将 v 的每个值赋值给每个变量
'''
#连续值 赋值
range(7)
print(range(7))
(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)
print(str(MONDAY)+' '+str(TUESDAY)+' '+str(SUNDAY))
| false |
23cfcfeabd2df7ce7a2b04037c4cf23dbc423c7f | Rockyzsu/StudyRepo | /python/basic/testPythonDemo.py | 1,707 | 4.15625 | 4 | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#使unicode编码能识别中文
#python是对大小写敏感的
print "hello, Python!";
name = raw_input('please enter your name: ');
#Integer a = (Integer)raw_input('please enter the number: ');
#This variable itself is not a fixed type of language, called a dynamic language, and corresponds to a static language.
b = 123;
c = 'abc';
print b,c;
#下面是java中静态变量的赋值
#aaa is an integer type variable
#int aaa = 123;
#aaa = "ABC"; #Error: string cannot be assigned to an integer variable
print ord('A'), chr(65);
#输出中文
print u'中文';
print '\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8');
print u'ABC'.encode('utf-8'), ',', u'中文'.encode('utf-8');
print 'Hello,', name, '!';
print '''line1
line2
lline3''';
#输出格式化的字符串
#在Python中,采用的格式化方式和C语言是一致的,用%实现
#%d 整数 %f 浮点数 %s 字符串 %x 十六进制整数
#格式化整数和浮点数还可以指定是否补0和整数与小数的位数
print 'Hello, %s' % 'world';
print 'Hi, %s, you have $%d.' % ('Michael', 1000000);
print '%2d-%02d' % (3, 1), '%.2f' % 3.1415926;
#如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串
print 'Age: %s. Gender: %s' % (25, True);
#用%来转义字符
print 'growth rate: %d %%' % 7;
#list
#list是一种有序的集合,可以随时添加和删除其中的元素
classmates = ['afa', 'axing','ahua'];
print classmates,',', len(classmates),',', classmates[0], classmates[1], classmates[2];
print classmates[-1], classmates[-2], classmates[-3];
classmates.append('Adam');
print classmates;
classmates.pop();
print classmates; | false |
f183bd60b67c7d608a547b37595ff7a0d14dbe21 | DamonGeorge/NLP | /project_03/proj3.py | 1,315 | 4.15625 | 4 | '''
WRITTEN FOR PYTHON 3
Team Member #1: Robert Brajcich
Team Member #2: Damon George
Zagmail address for team member 1: rbrajcich@zagmail.gonzaga.edu
Project 3: Extracts tokenized inaugural addresses from pickle file ('proj3.pkl')
and finds the frequency of a word in each address
Due: 9/14/2018
'''
#import necessary libraries
import matplotlib.pyplot as plt
import pickle
def main():
#Load pickled list of addresses
with open('proj3.pkl', 'rb') as fin:
parsed_addresses = pickle.load(fin)
#get the word to search
search = input("Enter word to search: ")
search.strip('"\'') # remove quotes if grader tries to use them
search.lower(); # lower since tokenizing lowers all letters in the addresses
#dict to hold year:count
word_frequency = {}
#loop through each address
for address in parsed_addresses:
#initial frequency is 0
count = 0
#first word is the address file title
#parse year from first four letters of the title
year = int(address[0][:4])
#Increment the count if each word matches the input
for word in address[1:]:
if word == search:
count = count + 1
#add new values to dict
word_frequency[year] = count
#plot the year vs word count
plt.plot(word_frequency.keys(), word_frequency.values())
plt.xlabel('Year')
plt.ylabel('Word Count')
plt.show()
if __name__ == "__main__":
main()
| true |
0df613e039f1764bd2390b69096c65fb16494811 | bhatiakomal/pythonpractice | /Pythontutes/tut8.py | 1,892 | 4.21875 | 4 | mystr="harry is good boy"
print(len(mystr))
#len is used for determine lenght of string and counting is start from 0
print(mystr[0])
print(mystr[0:4])
print(mystr[0:5])
#this is called string slicing
print(mystr[0:18])
print(mystr[0:80])#we don't have string of 80 but system can give us upto its length
print(mystr[0:5:2])
print(mystr[0:])#it takes full length of string
print(mystr[:5])#it takes 0 by default
print(mystr[: :])#it also write whole string [0:length:1]
print(mystr[::2])#it left one character and one takes and so on
print(mystr[::3])#it left two character and one takes and so on
print(mystr[::9])
print(mystr[::68778])#This all is clled extended slicing
print(mystr[-4:-2])#if -ve sign is occur then start learning string from behind
print(mystr[13:15])#we can change -ve sign with +ve sign by count all charater from starting
print(mystr[::-1])#this can make string opposite
print(mystr[::-2])#ye pehle string ko ulta krega after that ye 1 character skip krega
#Some other functions
print(mystr.isalnum())
mystr="harryisgoodboy"
print(mystr.isalnum())#if we remove space from string output is true but if dont then it is false
mystr="harry is goodboy"
print(mystr.isalpha())
mystr="harryisgoodboy"
print(mystr.isalpha())
mystr="harry is goodboy"
print(mystr.endswith("boy"))
mystr="harry is goodboy"
print(mystr.endswith("bdoy"))
mystr="harry is goodboy"
print(mystr.count("b"))
mystr="harry is goodboy"
print(mystr.count("o"))
mystr="harry is goodboy"
print(mystr.capitalize())
mystr="harry is goodboy"
print(mystr.find("is"))
mystr="harry is goodboy"
print(mystr.lower())
mystr="harry is goodboy"
print(mystr.upper())
mystr="harry is goodboy"
print(mystr.replace("is","was"))
mystr="harry is goodboy"
print(mystr.title())
mystr="harry is goodboy"
print(mystr.strip())
mystr="harry is good boy"
print(mystr.startswith(""))
mystr="harry is goodboy"
print(mystr.splitlines())
| true |
f347546a3cc7b50be89816f2772370c661e33a74 | bhatiakomal/pythonpractice | /Pythontutes/NestedIfElseStatement.py | 324 | 4.3125 | 4 | """a=5
b=2
c=6
d=3
if a>b:
print("true")
if c>d:print("c is greater then d")
else:print("d is greater then c")
else:
print("b is greater then a")"""
a=5
b=8
c=6
d=3
if a>b:
print("true")
if c>d:print("c is greater then d")
else:print("d is greater then c")
else:
print("b is greater then a") | false |
238a74a3e89f96a59cd779df4181c849f9e5e4eb | bhatiakomal/pythonpractice | /Practice/Practice68.py | 806 | 4.15625 | 4 | def show():
primarycolour1=input("Please enter first colour:")
primarycolour2=input("Please enter second colour:")
if primarycolour1=="red" and primarycolour2=="blue" or \
primarycolour1=="blue" and primarycolour2=="red":
print(primarycolour1+" is mixed with "+primarycolour2+" is purple ")
elif primarycolour1=="red" and primarycolour2=="yellow" or \
primarycolour1=="yellow" and primarycolour2=="red":
print(primarycolour1 + " is mixed with " + primarycolour2 + " is orange")
elif primarycolour1=="blue" and primarycolour2=="yellow" or \
primarycolour1=="yellow" and primarycolour2=="blue":
print(primarycolour1 + " is mixed with " + primarycolour2 + " is green")
else:
print("Error:Out of the course")
show()
| true |
8d2a5610d4fe6f9fd95a704eb4e7a2056269a8ad | bhatiakomal/pythonpractice | /Pythontutes/GettingInputFromUserInTuple.py | 539 | 4.28125 | 4 | '''a=[]
n=int(input("Enter number of element:"))
for i in range(n):
a.append(int(input("Enter element:")))
print(type(a))
a=tuple(a)
print(type(a))
print("tuples")
for j in a:
print(j)
#Repition in Tuple
print("Repition in Tuple")
a=(10,20,30,40,50)
b=a*5
print(b)
#Aliasing in tuple
print("Aliasing in tuple")
a=(10,20,30,40,50)
b=a
print(a)
print(b)
print("A:",id(a))
print("b:",id(b))
a=(10,20,30,40,50)
b=a
a=a[:3]
print(a)
print(id(a))
print(b)
print(id(b))'''
print("copying tuple")
a=(10,20,30,40,50)
b=a[0:5]
print(b)
| false |
bf120c4fb558764f85013c8040160517d39f2072 | arxaqapi/99-solutions | /Python/1_01.py | 515 | 4.28125 | 4 | # Find the last element of a list
def find_last_element(given_list):
if given_list == []:
return "given_list is empty"
return given_list[-1]
def find_last_element_2(given_list):
if given_list == []:
return "given_list is empty"
return given_list[len(given_list) - 1]
def find_last_element_3(given_list):
list_lenght = 0
for i in range(given_list):
list_lenght += 1
if list_lenght == 0:
return "given_list is empty"
return given_list[list_lenght]
| true |
9cf885a250bc9f9a4a2144c2c83fa9691871014d | stjohn/stjohn.github.io | /teaching/cmp/cis166/s15/mines.py | 1,609 | 4.15625 | 4 | from turtle import *
from random import *
""" Sets up the screen with the origin in upper left corner """
def setUpScreen(xMax,yMax):
win = Screen()
win.setworldcoordinates(-0.5, yMax+0.5,xMax+0.5,-0.5)
return win
""" Draws a grid to the graphics window"""
def drawGrid(xMax,yMax):
tic = Turtle()
tic.speed(10)
#Draw the vertical bars of the game board:
for i in range(0,xMax+1):
tic.up()
tic.goto(0,i)
tic.down()
tic.forward(yMax)
#Draw the horizontal bars of the game board:
tic.left(90) #Point the turtle in the right direction before drawing
for i in range(0,yMax+1):
tic.up()
tic.goto(i,0)
tic.down()
tic.forward(xMax)
def createMines(numMines, side):
grid = [[""]*side]*side
n = 0
while n < numMines:
#Generate a new mine:
x = randrange(side)
y = randrange(side)
if grid[x][y] == "":
grid[x][y] = "X"
n = n + 1
return grid
def main():
side=10
numMines = 40
foundMines = 0
squaresLeft = side*side
exploded = 0
setUpScreen(side,side)
drawGrid(side,side)
grid = createMines(numMines,side)
while foundMines < numMines:
x,y = eval(input('Enter x,y (separated by comma): '))
kind = input('Type "M" for mine (anything else for empty cell):')
if grid[x][y] == "X":
foundMines = foundMines + 1
if kind == "M" or kind == "m":
print("You found a mine!")
main()
| true |
27991d0731342e22aa2081f0e365afa31e732b8c | stjohn/stjohn.github.io | /teaching/cmp/cmp230/s13/squareTurtle.py | 380 | 4.1875 | 4 | import turtle
def main():
daniel = turtle.Turtle() #Set up a turtle named "daniel"
myWin = turtle.Screen() #The graphics window
#Draw a square
for i in range(4):
daniel.forward(100) #Move forward 10 steps
daniel.right(90) #Turn 90 degrees to the right
myWin.exitonclick() #Close the window when clicked
main()
| true |
0f9fdc457fa64320e807661486625d905d632758 | stjohn/stjohn.github.io | /teaching/cmp/cmp230/s14/TurtleBall.py | 1,136 | 4.3125 | 4 | #A simple class, demonstrating constructors and methods in python
#Intro Programming, Lehman College, CUNY, Spring 2014
from turtle import *
class TurtleBall:
def __init__(self,color):
__init(self,color,45,-100,-100,100,100)
def __init__(self,color,angle,x1,y1,x2,y2):
self.turtle = Turtle()
self.turtle.color(color)
self.turtle.shape("circle")
self.turtle.left(angle)
self.turtle.speed(0)
self.xMin,self.yMin,self.xMax,self.yMax = x1,y1,x2,y2
def move(self,d):
for i in range(d):
x,y = self.turtle.pos()
angle = self.turtle.heading()
if (x > self.xMax-4 or x < self.xMin+4)\
and (y > self.yMax-4 or y < self.yMin+4):
self.turtle.left(180)
elif x > self.xMax-4 or x < self.xMin+4:
self.turtle.left(180-2*angle)
elif y > self.yMax-4 or y < self.yMin+4:
self.turtle.left(360-2*(angle))
self.turtle.forward(5)
def getTurtle(self):
return self.turtle
def setTurtle(self, value):
self.turtle = value
| false |
1eeaffa5201149d55e002072ba5d075dcda5661d | shahazad08/Bridgelabz_Shahazad | /Algorithms/ds.py | 325 | 4.21875 | 4 | def pallindrome():
try:
n = int(input("Entee rthe Nos"))
n1=str(n)
a=n1[::-1]
if(a==n1):
print("Given Nos. is Pallindrome",a)
else:
print("Not the Pallindrome Nos")
#return 0
except ValueError:
print("Enter the Valid String")
pallindrome() | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.