blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2e70c50fcab2e05f45206cdc6dbe1148ee4b5967 | D1egoS4nchez/Ejercicios | /Ejercicios/ejercicio50.py | 859 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Confeccionar un programa que permita ingresar un valor del 1 al 10 y nos muestre la tabla de multiplicar del mismo (los primeros 12 términos)
Ejemplo: Si ingreso 3 deberá aparecer en pantalla los valores 3, 6, 9, hasta el 36."""
"""numero = int(input("Ingrese el numero del 1 al 10 que quiere multiplicar: \n"))
print("-------")
for f in range(1,11):
multiplicacion = numero * f
print(multiplicacion)
"""
numero = int(input("Ingrese el numero del 1 al 10 que quiere multiplicar: \n"))
if numero in range(10):
regreso = True
else:
regreso = False
while regreso == False:
numero = int(input("Ingrese el numero del 1 al 10 que quiere multiplicar: \n"))
if numero <= 10:
regreso = True
for f in range(1,11):
multiplicacion = numero * f
print(multiplicacion)
| false |
fe2da772c006b138e27ac96d628055f65672cc05 | widodom/hello-world | /LoopsTest.py | 779 | 4.3125 | 4 |
days=["Monday", "Tuesday", "Wednesday", 35]
# print(days)
#this is a "for loop"
for apple in days:
if isinstance(apple, int):
print("{} is a number".format(apple))
else:
print("today is {}".format(apple))
for x in range(1,0, -1):
print("the number is {} and the next number is {}".format(x, x+1))
#string format syntax example above
#days is a list. Ranges are different from lists in that Ranges only works for numbers. Lists explictly define
#Range is inclusive of the start and exclusive of the end. -1 backwards
#apple is the name of a variable.
#String Interpolation
#If (Condition) Boolean decision. Truthy
#"None" is Python specific same as "Null" in C
#Truthy False includes None. 0, False, [], and "". Truthy True -everything else.
| true |
582dde77c84e44662b8ceecd90c7c3f67a92f6e5 | jaoist/primer | /primer.py | 1,138 | 4.15625 | 4 | def mean(set):
"""Takes a list of of objects and attempts to find the mean"""
s = 0
for n in set:
s = n + s
m = s / len(set)
return m
def median(set):
"""Returns the median value of a set"""
set.sort()
width = len(set)
middle_val = int(width / 2)
if (width % 2) == 0:
m = set[middle_val - 1] + set[middle_val]
m = m / 2
return m
else:
m = set[middle_val]
return m
def mode(set):
"""Returns the number with the most occurences in a set."""
# To get the mode we need to look for numbers that occur more than once in
# the set. We could store number / occurence pairs in a dict. Or we could
# store the the values in two variables. Check all numbers against each
# each value in a set and save the values that have the highest count.
# Or we could construct lists of the occurences of each value and check the
# length of the list.
set.sort()
def even(n):
"""Returns True if parity of number is even, false if odd."""
if (n % 2) == 0:
return True
else:
False | true |
0035ab33dd51031c4462eb085298748cabc6a87f | kseniajasko/Python_study_beetroot | /hw29/hw29_task1.py | 1,469 | 4.28125 | 4 | # A bubble sort can be modified to “bubble” in both directions.
# The first pass moves “up” the list and the second pass moves “down.”
# This alternating pattern continues until no more passes are necessary.
# Implement this variation and describe under what circumstances it might be appropriate.
import random
# def bubble_sort(array):
# n = len(array)
# for k in range(n - 1, 0, -1):
# for l in range(k):
# if array[l] > array[l + 1]:
# array[l], array[l + 1] = array[l + 1], array[l]
def shaker_sort(array):
n = len(array)
swapped = True
start = 0
end = n - 1
while swapped is True:
swapped = False
# from left to right
for k in range(start, end):
if array[k] > array[k + 1]:
array[k], array[k + 1] = array[k + 1], array[k]
swapped = True
# if not exchanges
if not swapped:
break
swapped = False
end -= 1
# from right to left
for l in range(end - 1, start-1, -1):
if array[l] > array[l + 1]:
array[l], array[l + 1] = array[l + 1], array[l]
swapped = True
start += 1
if __name__ == "__main__":
test_list = [random.randint(1, 100) for _ in range(10)]
print(test_list)
copy_test_list = test_list[:]
# bubble_sort(copy_test_list)
shaker_sort(copy_test_list)
print(copy_test_list)
| true |
52fe943caba7fc8d9c138d494384a53ea79fb755 | kseniajasko/Python_study_beetroot | /hw26/hw26_task_2.py | 1,621 | 4.28125 | 4 | # Write a program that reads in a sequence of characters,
# and determines whether it's parentheses, braces, and curly brackets are "balanced."
from Stack import Stack
def AreBracketsBalanced(expr):
if not expr:
return 'Empty'
stack = Stack()
# Traversing the Expression
for char in expr:
if char in ["(", "{", "[", "<"]:
# Push the element in the stack
stack.push(char)
else:
# IF current character is not opening
# bracket, then it must be closing.
# So stack cannot be empty at this point.
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ")":
stack.push(current_char)
break
if current_char == '{':
if char != "}":
stack.push(current_char)
break
if current_char == '[':
if char != "]":
stack.push(current_char)
break
if current_char == '<':
if char != ">":
stack.push(current_char)
break
# Check Empty Stack
if stack.size() == 0:
return "Balanced"
else:
return "Unbalanced"
if __name__ == "__main__":
string1 = "{[]{()}}"
print(string1, "-", AreBracketsBalanced(string1))
string2 = "[{}{})(]"
print(string2, "-", AreBracketsBalanced(string2))
string3 = "((()"
print(string3, "-", AreBracketsBalanced(string3)) | true |
7608feb942b23f4c635bf2cea0320b692a606b75 | ujjwalkumar10/HacktoberFest-21 | /Middle-Of-Linked-List.py | 743 | 4.21875 | 4 | # Python program to find the middle of a given linked list
class Node:
def __init__(self, value):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# create Node and and make linked list
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printMiddle(self):
temp = self.head
count = 0
while self.head:
# only update when count is odd
if (count & 1):
temp = temp.next
self.head = self.head.next
# increment count in each iteration
count += 1
print(temp.data)
# Driver code
llist = LinkedList()
llist.push(1)
llist.push(20)
llist.push(100)
llist.push(15)
llist.push(35)
llist.printMiddle()
| true |
82d0d3f122baa586e61946eb41d04fa49250c136 | manasakaveri/CI-CD | /PycharmProjects/CI/Arg.py | 469 | 4.28125 | 4 | def print_two(*args):
arg1 ,arg2 =args
print(f"arg1:{arg1},arg2 : {arg2 }")
# ok ,thatt *args is actually pointless,we an just do this
def print_two_again(arg1,arg2):
print(f"arg1:{arg1},arg2 : {arg2}")
#this just takes one argument
def print_one(arg1 ):
print(f"arg1:{arg1}")
#this one takes no arguments
def print_none():
print("I got nothing")
print_two("Manasa","Aditi")
print_two_again("Manasa","Aditi")
print_one("First !")
print_none()
| false |
d6c972d955e2789e6c000205aa7ff22215911f9a | skafis/python-essentials | /search.py | 448 | 4.1875 | 4 | import re
with open('text.txt')as text:
# text = f.readlines()
#text = input("enter text or paragraph to search\n")
find = input("enter the word you want to search\n")
for line in text:
if find in line:
print (line)
# print (text)
# if re.search(r"[find]",text, re.M):
# print (find + " has been found")
# else:
# print("sorry "+find+ " cant be found try another word")
| true |
d6aa50e2cc2646227819d19fc9babe5b00409150 | IgorPereira1997/Python-SQL-Basics | /pratica_funcionalidades/listas.py | 495 | 4.375 | 4 | #-*- coding: utf-8 -*-
frutas = ["abacaxi", "melancia", "avocado"]
print(len(frutas))
# add items to the list
frutas.append("strawberry")
#verify if an item is on the list
try:
print(frutas.index("banana"))
except:
print("'banana' is not on the list!")
#delete list
del(frutas)
numeros = [1, 56, 14, 67, 129, 4, 35, 7, 2, 90]
#sort items
numeros.sort()
# reverse sort ==> numeros.sort(reverse=True)
#inverse list ==> numeros.inverse()
numeros = sorted(numeros)
print(numeros)
| true |
f4016e14a19076988d0a993449b61fa7752da439 | fm359/CS260 | /PA2/mergelists.py | 2,168 | 4.1875 | 4 | #!/usr/bin/env python
from arraylist import *
#Exercise 2.3, using arraylist from PA1
#sorts all elements of the given arraylist
def insertionsort(List):
for i in range(0, List.end()):
j = i
while j > 0 and List.retrieve(j) < List.retrieve(j - 1):
List.elements[j], List.elements[j - 1] = List.elements[j - 1], List.elements[j]
j -= 1
#merges and sorts two arraylists
def mergetwolists(L1,L2):
merged_list = L1
for i in range(0,L2.end()):
elem = L2.retrieve(i)
merged_list.insert(elem, merged_list.end())
insertionsort(merged_list)
return merged_list
#merges and sorts an arraylist of arraylists
def mergenlists(Lists):
merged_list = arraylist()
i = 0
while i < Lists.end():
list = Lists.retrieve(i)
for j in range(0,list.end()):
elem = list.retrieve(j)
merged_list.insert(elem, merged_list.end())
i += 1
insertionsort(merged_list)
return merged_list
print "mergelists.py merged_lists"
print
print "Merge two sorted lists, both [a,b,c,d,e]:"
print "Should return a a b b c c d d e e"
test_list1 = arraylist()
test_list1.insert("a", 0)
test_list1.insert("b", 1)
test_list1.insert("c", 2)
test_list1.insert("d", 3)
test_list1.insert("e", 4)
test_list1 = mergetwolists(test_list1, test_list1)
for i in range(0, test_list1.end()):
print test_list1.retrieve(i)
print
print "Merge n sorted lists with numbers as elements:"
print "Should return numbers 0 - 10"
test_list1 = arraylist()
test_list1.insert(0, 0)
test_list1.insert(2, 1)
test_list1.insert(6, 2)
test_list1.insert(8, 3)
test_list2 = arraylist()
test_list2.insert(1, 0)
test_list2.insert(5, 1)
test_list2.insert(3, 2)
test_list2.insert(9, 3)
test_list3 = arraylist()
test_list3.insert(4, 0)
test_list3.insert(10, 1)
test_list3.insert(7, 2)
merged_lists = arraylist()
merged_lists.insert(test_list1, 0)
merged_lists.insert(test_list2, 1)
merged_lists.insert(test_list3, 2)
merged_lists = mergenlists(merged_lists)
for i in range(0, merged_lists.end()):
print merged_lists.retrieve(i)
| true |
16c8c968b613d56c9081c595d96c7a05086b8ec0 | CoreyDeJong/data-structures-and-algorithms-python | /data_structures/graphs/stacks_and_queues.py | 2,003 | 4.25 | 4 | from collections import deque
# referenced multiple internet sites for examples
class Stack():
def __init__(self):
self.top = None
def __repr__(self):
return f"Top is {self.top}"
def push(self, value):
new_node = Node(value, self.top)
self.top = new_node
def pop(self):
if self.top == None:
raise Exception ("empty stack")
else:
pop_node = self.top
self.top = self.top.next
pop_node.next = None
return pop_node.value
def peek(self):
if self.top != None:
return self.top.value
else:
return "empty stack"
def is_empty(self):
if self.top == None:
return True
else:
return False
class Queue():
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, value):
new_node = Node(value)
if self.rear == None:
self.front = new_node
self.rear = self.front
else:
self.rear.next = new_node
self.rear = self.rear.next
def dequeue(self):
if self.front != None:
temp_node = self.front
self.front = self.front.next
if self.front == None:
self.rear = None
temp_node.next = None
return temp_node.value
else:
return "empty queue"
def peek(self):
if self.front != None:
return self.front.value
else:
return "empty queue"
def is_empty(self):
if self.front == None:
return True
else:
return False
class Node():
def __init__(self, value, next_=None):
self.value = value
self.next = next_
if not isinstance(next_, Node) and next_ != None:
raise TypeError("Next must be a Node")
def __repr__(self):
return f"{self.value} : {self.next}"
| true |
989ffafbab6da7c8f5ed64bf35b0afb75149d91f | CoreyDeJong/data-structures-and-algorithms-python | /data_structures/hashtable/linked_list.py | 1,154 | 4.21875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
# if list is empty
if not self.head:
self.head = node
else:
current = self.head
# will keep going through the linked list while a current.next is true, it will make the next node current and then repeat until there is no more next nodes
while current.next:
current = current.next
# once there are no more next nodes, you will make a new node
current.next = node
def display(self):
values = []
current = self.head
while current:
values.append(current.data)
current = current.next
return values
def __str__(self):
""" { a } -> { b } -> { c } -> NULL """
final_string = ""
current = self.head
while current:
final_string += f"{{{current.data}}} -> "
current = current.next
return f"{final_string} NULL" | true |
c4c90d3913fba2205d2bb7af6e0d21d0c98ed7e7 | leiz2192/Python | /exercise/rotate-string/rotate-string.py | 738 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str, offset):
if not str:
return str
if offset < 0:
return str
str_size = len(str)
offset = offset % str_size
right_rotate = str[:(str_size - offset)]
left_rotate = str[(str_size - offset):]
after_rotate = left_rotate + right_rotate
return after_rotate
def main():
str = "abcdefg"
print(Solution().rotateString(str, 2))
print(Solution().rotateString("abcdefg", 3))
print(Solution().rotateString("abc", 2))
if __name__ == '__main__':
main()
| true |
1ee44e915045d21ecd09ca06b8d4100c5d359f50 | leiz2192/Python | /exercise/longest-words/longest-words.py | 852 | 4.125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
class Solution:
"""
@param: dictionary: an array of strings
@return: an arraylist of strings
"""
def longestWords(self, dictionary):
max_word_len = 0
words_statistics = {}
for one_word in dictionary:
word_len = len(one_word)
if word_len > max_word_len:
max_word_len = word_len
if word_len in words_statistics:
words_statistics[word_len].append(one_word)
else:
words_statistics[word_len] = [one_word]
return words_statistics[max_word_len]
def main():
print(Solution().longestWords({"dog", "google", "facebook", "internationalization", "blabla"}))
print(Solution().longestWords({"like", "love", "hate", "yes"}))
if __name__ == '__main__':
main()
| false |
76ef4ff724859fb1a263bae3bba2d317d758f268 | vsapucaia/python_unittest | /assert_tests/happynumbers.py | 558 | 4.15625 | 4 | """
A number is considered happy when:
1. Given a specific integer number
2. Replace the number with the sum of the square of its digits. 47 = 4² + 7²
3. If it ends resulting 1, the number is happy
4. If not, repeat the process indefinitely
1, 7, 10, 13, 19: happy
"""
def happy_number(number):
next_ = sum([int(char) ** 2 for char in str(number)])
return number in (1, 7) if number < 10 else happy_number(next_)
if __name__ == '__main__':
for n in range(200):
print(str(n) + ': ' + ('happy' if happy_number(n) else 'not happy'))
| true |
1663add3f1b3329b0c0b0f563918a803cf6379cf | python-zak/learning-python | /text/pig_latin.py | 340 | 4.34375 | 4 | # To create the Pig Latin form of an English word the initial consonant sound is transposed
# to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay)
def pig_latin(word):
new_word = word[1:] + word[0] + 'ay'
return new_word
if __name__ == '__main__':
p = input('enter text:')
print(pig_latin(p)) | true |
be1b22931d637df369df2b0450eae036baebdccc | espazo/sicp-in-python | /2 使用对象构建抽象/列表和字典的实现.py | 2,678 | 4.28125 | 4 | empty_rlist = None
def make_rlist(first, rest):
"""Make a recursive list from its first element and the rest."""
return (first, rest)
def first(s):
"""Return the first element of a recursive list s."""
return s[0]
def rest(s):
"""Return the rest of the elements of a recursive list s."""
return s[1]
def len_rlist(s):
"""Return the length of recursive list s."""
length = 0
while s != empty_rlist:
s, length = rest(s), length + 1
return length
def getitem_rlist(s, i):
"""Return the element at index i of recursive list s."""
while i > 0:
s, i = rest(s), i - 1
return first(s)
def make_mutable_rlist():
"""Return a functional implementation of a mutable recursive list."""
contents = empty_rlist
def dispatch(message, value=None):
nonlocal contents
if message == 'len':
return len_rlist(contents)
elif message == 'getitem':
return getitem_rlist(contents, value)
elif message == 'push_first':
contents = make_rlist(value, contents)
elif message == 'pop_first':
f = first(contents)
contents = rest(contents)
return f
elif message == 'str':
return str(contents)
return dispatch
def to_mutable_rlist(source):
"""Return a functional list with the same contents as source."""
s = make_mutable_rlist()
for element in reversed(source):
s('push_first', element)
return s
# 消息传递
def make_dict():
"""Return a functional implementation of a dictionary."""
records = []
def getitem(key):
for k, v in records:
if k == key:
return v
def setitem(key, value):
for item in records:
if item[0] == key:
item[1] = value
return
records.append([key, value])
def dispatch(message, key=None, value=None):
if message == 'getitem':
return getitem(key)
elif message == 'setitem':
return setitem(key, value)
elif message == 'keys':
return tuple(k for k, _ in records)
elif message == 'values':
return tuple(v for _, v in records)
return dispatch
if __name__ == '__main__':
suits = ['heart', 'diamond', 'apade', 'club']
s = to_mutable_rlist(suits)
print(type(s))
print(s('str'))
print(s('pop_first'))
d = make_dict()
d('setitem', 3, 9)
d('setitem', 4, 16)
print(d('getitem', 3))
print(d('getitem', 4))
print(d('keys'))
print(d('values'))
c = make_dict()
print('c', c('keys'))
| true |
fed0d14e5bb671f0f41c2f998be55ac20d0d2c05 | coolspaceninja/woke-src | /guess_val2.py | 1,824 | 4.28125 | 4 | # Warning: Modifying the computer_benefit may cause huge and lengthy output
import random
def main():
#Global bounds for the game
x = 1
y = 99
usr_secret = input("Think of a number between " + str(x)+"and" + str(y)+ ". The computer shall try to guess it: ")
#Checking that users value are valid, adjusting them if not
if usr_secret > y:
usr_secret = y
elif usr_secret < x:
usr_secret = x
while(True):
#Difficulty settings:
computer_guess = random.randint(x,y)
#The benefit setting controls the steps the computer can go higher/lower
#based on last guess
computers_benefit = 16
if computer_guess == usr_secret:
print("Computer: Success, it was " + str(usr_secret) + "! I read you like an open book, human!")
break
else:
if computer_guess > usr_secret:
print("Computer: I shall aim lower")
#This loop hastens computers guessing ability by putting the ceiling of
# its guesses closer to the answer,
# but it does not make its random ceiling go out of bounds
while(y > usr_secret and computers_benefit > 0):
y-=1
computers_benefit-=1
else:
print("Computer: I shall aim higher")
#This loop hastens computers guessing ability by putting the lower bound of
# its guesses closer to the answer,
# but it does not make its random lower bound go out of bounds
while(x < usr_secret and computers_benefit > 0):
x+=1
computers_benefit-=1
if __name__ == "__main__":
main() | true |
32a26e9519221c14baf7ebf823c8bf80a70721ab | HaoYun519/Python | /彭彭Python入門/instance-example/instance-1.py | 568 | 4.25 | 4 | # Point 實體物件的設計: 平面座標上的點
# class Point:
# def __init__(self, x, y):
# self.x=x
# self.y=y
# # 建立第一個實體物件
# p1=Point(3,4)
# print(p1.x, p1.y)
# # 建立第二個實體物件
# p2=Point(5,6)
# print(p2.x, p2.y)
# FullName 實體物件的設計,分開紀錄姓,名資料的全名
class FullName:
def __init__(self, first, last):
self.first=first
self.last=last
name1=FullName("H.Y.", "Siao")
print(name1.first, name1.last)
name2=FullName("I.W.", "Huang")
print(name2.first, name2.last) | false |
dbc8cb3f3884fe05e174ea8d2024d89ccd1aaa8a | MinasMayth/RUG_university_work | /Python_Programming/Homework 3.py | 2,564 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 12:59:33 2020
Homework 3!
@author: samya
"""
import random
import matplotlib.pyplot as plt
import numpy as np
def rand_list_gen():
length = int(input("What length should the list be? "))
numbers = []
for x in range (0,length):
numbers.append(round(random.random(),3))
print(numbers)
return(numbers)
def rand_list_calc(x):
list_sum = 0
for i in numbers:
list_sum += i
print ("The sum of all numbers in the list is %.3f." % list_sum )
list_avg = list_sum/len(numbers)
print ("The average of all numbers in the list is %.3f." % list_avg)
def circle_plotter():
circle1 = plt.Circle((5, 5), 2, color='blue')
ax = plt.gca()
ax.cla()
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
ax.add_artist(circle1)
plt.savefig('plotcircles.png')
plt.show()
def negative_replacer():
list_of_integers = []
for x in range (0,10):
list_of_integers.append(round(random.randint(-10,10)))
print(list_of_integers)
positive_list = [i if i >= 0 else 0 for i in list_of_integers]
print(positive_list)
def list_operations():
a = []
b = []
for x in range (0,10):
a.append(round(random.randint(0,10)))
for x in range (0,10):
b.append(round(random.randint(0,10)))
print (a)
print (b)
decision = input(" '+' or '-'? ")
if decision == "+":
c = list(np.array(a) + np.array(b))
elif decision == "-":
c =list(np.array(a) - np.array(b))
print(c)
if __name__ == "__main__":
while True:
print("Which program do you want to run?")
print("1. Random list generator")
print("2. Random list calculator (RUN 1 BEFORE RUNNING THIS)")
print("3. Circle plotter")
print("4. Negative integer replacer")
print("5. List operations tester")
print("Or type 'exit' to leave the program!")
menu_decision = input().upper()
if menu_decision == "1":
numbers = rand_list_gen()
elif menu_decision == "2":
rand_list_calc(numbers)
elif menu_decision == "3":
circle_plotter()
elif menu_decision == "4":
negative_replacer()
elif menu_decision == "5":
list_operations()
elif menu_decision == "EXIT":
break
else:
print("Invalid input.") | true |
961224166123f71ddf4b489c21c6618d66a5ab5e | DanielMevs/Fun-With-Matrices-in-Python | /numpy/ndarray_properties.py | 305 | 4.21875 | 4 | import numpy as np
x = np.array([[2,3],[1,4],[5,7]])
print(x)
#returns a tuple with the size of the array
#here shape is synonomous with size
shape = x.shape
print(shape, "\n")
#reshapes the array to a 2 by 3
new_x = x.reshape(2,3)
print(new_x)
shape = new_x.shape
print(shape)
x[0][1] = 9
print(x)
| true |
296a5eb3dc2860961b356795b83e15275485d130 | guren-ev/sqlTest | /01_sql.py | 458 | 4.4375 | 4 | # Real Python book, script to create a DB
# Create a SQLite Database and table
# import sqlite3 ibrary
import sqlite3
# create a new database if it does not exist
conn = sqlite3.connect("new.db")
# get a cursor object used to execute SQL commands
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE population
(city TEXT, state TEXT, population INT)
""")
#close the database connection
conn.close()
| true |
bf67678b87b2bdb4ef78db911ee6c5bdf7c5cf1d | tknmk/get_smallest_number | /get_min_max_numbers.py | 284 | 4.15625 | 4 | # -*- coding: utf-8 -*-
lst = []
num = int(input('Enter number of elements in lis: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is : ", max(lst))
print("Minimum element in the list is : ", min(lst))
| true |
91ca3dbadd33eebbf938e2266665f8bcaa1db868 | TiagoFar/PythonTeste | /Aula 09 B.py | 706 | 4.15625 | 4 | # TRANSFORMAÇÃO
frase = ('Tiago de Oliveira Faria')
print(frase.replace('Faria','Gostoso')) # troca por uma existente
print(frase.upper()) #todas maiúsculas
print(frase.lower()) # todas minúsculas
print(frase.capitalize()) # só a primeira maiúscula
print(frase.title()) # primeiras letras maiúsculas
frase = (' Tiago de Oliveira Faria ')
print(frase.strip()) # remove os espaços em branco, desnecessários, antes e depois da frase.
print(frase.rstrip()) # remove os últimos espaços da direita
print(frase.lstrip()) # remove os espaços da esquerda
#DIVISãO
print(frase.split()) # dividido em uma lista, palavra por palavra.
#JUNÇÂO
print('-'.join(frase))
print("""Irá escrever um texto inteiro se tiver entre 3 aspas""")
| false |
06d2de9b95f26937e55148e6c4be1142d6734a1e | TiagoFar/PythonTeste | /Aula 08 A.py | 620 | 4.21875 | 4 | import math # << importa todas as funcionalidades
# from math import sqrt << vai importar só a raiz quadrada e não irá precisa mais a "math" para chamar a raiz!
n = int(input('Digite um número: '))
raiz = math.sqrt(n) # aqui não precisa chamar a raiz se ela foi importada com o "from math import sqrt".
print('A raiz quadrada de {} é {}.'.format(n,raiz))
print('A raiz quadrada de {} arredondado pra cima é {}.'.format(n, math.ceil(raiz)))
print('A raiz quadrada de {} arredondada pra baixo é {}.'.format(n, math.floor(raiz)))
print('A raiz quadrada de {} é {:.2f} com formatação de 2 casas'.format(n, raiz)) | false |
483581688beaf24d974016c3a074d2bcbc0a8cef | Kaloslmr/Python-Pensamiento | /29_listComprehension3.py | 389 | 4.1875 | 4 | #Lista Example:
lista = [valor for valor in range(0, 101) if valor % 2 == 0]
#1- valor a agregar en la lista (VALOR)
#2- un ciclo, for
#3- si queremos un condicional!
print(lista)
#Tupla Example:
tupla = tuple((valor for valor in range(0, 101) if valor % 2 != 0))
print(tupla)
#Diccionario Example:
diccionario = {indice:valor for indice, valor in enumerate(lista)}
print(diccionario) | false |
16ea11336820b1743434b21e8b5260fba9efa4f3 | Gporfs/Python-s-projects | /brasileirão.py | 1,024 | 4.15625 | 4 | times = ('Internacional', 'Flamengo', 'Atlético-MG', 'São Paulo',
'Fluminense', 'Palmeiras', 'Grêmio', 'Santos', 'Athlético-PR',
'Corinthians', 'Bragantino', 'Ceará-SC', 'Atlético-GO', 'Sport Recife',
'Fortaleza', 'Bahia', 'Vasco', 'Goiás', 'Coritiba', 'Botafogo')
titulo = 'BRASILEIRÃO 2021'
print('='*30)
print(f'{titulo:^30}')
print('='*30)
print('OS PRIMEIROS COLOCADOS DO BRASILEIRÃO SÃO:')
cont = 0
tops = 0
while not tops == 5:
print(times[tops])
tops += 1
print('OS ULTIMOS COLOCADOS SÃO:')
loosers = -1
while not loosers == -5:
print(times[loosers])
loosers -= 1
print('INTEGRANTES DESSE BRASILEIRAO:')
for t in sorted(times):
print(f'{t}')
time = str(input('Qual time você quer saber a posição? ')).title()
while time not in times:
time = str(input('Tente de novo. Qual time você quer saber a posição? '))
chapeco = times.index(time) + 1
print(f'{time} se encontra na posição {chapeco}ª posição do Brasileirão!')
| false |
62935908c4627553efb56227b38086a09a9e8cd8 | MVG8/new_project | /GeekBrains/lesson1/example4.py | 2,859 | 4.21875 | 4 | # ЦИКЛЫ While-(ПОКА)
# number = int(input('Введите целое число от 0 до 9: '))
# while number < 10:
# print(number)
# number = number + 1
# print('Программа завершена успешно!')
"""
Программа выводит на экран все числа — от введённого числа до 9, с шагом 1.
Например, если мы введём число 7, программа выведет 7, 8 и 9.
Вторая строка — это оператор цикла while и number < 10 — логическое выражение.
Третья и четвёртая строки — это тело цикла, которое будет выполняться до тех пор,
пока логическое выражение number < 10 будет истинно.
Пятая строчка не относится к телу цикла, так как перед ней нет отступа.
Сколько раз выполнится тело цикла, заранее неизвестно
— это зависит от заданного значения переменной number.
Обратите внимание на строчку 4.
При каждом выполнении этой строки в цикле её значение будет увеличиваться на единицу
до тех пор, пока значение переменной number не станет больше либо равно 10.
При этом значении логическое выражение number < 10 станет ложным, цикл завершится.
"""
#_______________ЗАЦИКЛИВАНИЕ_____________
"""
a = 5
while a > 0: # пока условие верно
print("!") # печатай восклицательный знак
a = a + 1
Запустив этот пример, вы увидите кучу восклицательных знаков, и так до бесконечности.
Цикл при текущих условиях не завершится никогда, потому что a всегда больше нуля,
условие a > 0 всегда будет верным. В программах нужно избегать бесконечных ,циклов.
"""
#*************BREAK and CONTINUE*********
i = 2
while True:
i += 1 # i = i + 1
if i >= 10:
# инструкция break при выполнении немедленно заканчивает
# выполнение цикла
break
if i % 2 == 0:
print(i, 'число делится нацело на два')
# переходим к проверке условия цикла,
# пропуская все операторы за инструкцией
continue
print(i)
| false |
917161a22ed30359154b0d29b98866823f618e92 | Mitesh227/The-smart-guess-game | /MY guess game.py | 604 | 4.25 | 4 | # My guess game
import random
random_number = random.randint(1, 10)
guess = int(input("Enter your guess number in between 1 to 10 \n"))
print(f"You have guess the number as {guess} ")
for i in range(0, random_number + 10):
if guess == random_number:
print("You got it right Congratulations!\n")
break
elif int(random_number) > guess:
print("oops your guess is Wrong! Get higher please\n ")
guess = int(input("Guess other number \n"))
else:
print("oops Your guess is Wrong! Get lower please\n ")
guess = int(input("Guess other number \n"))
| true |
654c231605ffea94400510f01d9129916ac2f84d | Hechizero15/PracticasPy | /pprograma.py | 1,745 | 4.3125 | 4 | # Un primer programa en python nada complicado
opc = 'S'
while (opc == 'S' or opc == 's'):
usr = raw_input('Hola, Ingresa tu nombre: ')
while (len(usr) == 0):
usr = raw_input('Debes Ingresar tu nombre para usar el programa.\nIngresa tu nombre: ')
num1 = raw_input('Ingrese un numero: ')
while (len(num1) == 0):
num1 = raw_input('Debes Ingresar un numero: ')
num1 = float(num1)
num2 = raw_input('Ingrese otro numero: ')
while (len(num2) == 0):
num2 = raw_input('Debes ingresar un segundo numero:')
num2 = float(num2)
# aqui empiezo con los calculos
print usr + ' La suma de sus numeros es: ' + str(int(num1+num2))
print 'Restando ' + str(num1) + ' - ' + str(num2) + ' el resultado es: ' + str(num1-num2)
print 'Restando ' + str(num2) + ' - ' + str(num1) + ' el resultado es: ' + str(num2-num1)
print 'La multiplicacion de sus numeros es: ' + str(num1*num2)
print 'Dividiendo ' + str(num1) + ' / ' + str(num2) + ' el resultado es: ' + str(num1/num2)
print 'Dividiendo ' + str(num2) + ' / ' + str(num1) + ' el resultado es: ' + str(num2/num1)
print 'Si elevamos ' + str(num1) + ' al exponente ' + str(num2) + ' el resultado es: ' + str(pow(num1, num2))
print 'Si elevamos ' + str(num2) + ' al exponente ' + str(num1) + ' el resultado es: ' + str(pow(num2, num1))
print 'La raiz cuadrada de '+ str(num1) +' es: ' + str(pow(num1, 0.5))
print 'La raiz cuadrada de '+ str(num2) +' es: ' + str(pow(num2, 0.5))
print 'La raiz ' + str(num2) + ' de ' + str(num1) + ' es: ' + str(pow(num1, 1/num2))
print 'La raiz ' + str(num1) + ' de ' + str(num2) + ' es: ' + str(pow(num2, 1/num1))
opc = raw_input('Desea continuar? (S/n): ')
while (len(opc) == 0):
opc = raw_input('Desea continuar? (S/n): ')
print 'Hasta luego '+ usr | false |
a67a3d7b2bb50a7bc965839cc43e9af56688e7ea | IMDCGP105-1819/portfolio-NormalUnicorn | /weekly_exercises_y1s1/ex11.py | 1,096 | 4.21875 | 4 | import random
def guesses(random_int):
'''
Asks the user to guess a number, it then compares if the number is the
same as the random number, if not it then sees if the number is greater than
or less than the user guess and will let the user know, and also add the guess
to a list
'''
past_guesses = []
guess = 0
while guess != random_int:
guess = int(input("Please enter a number to guess"))
if guess != random_int:
past_guesses.append(guess)
if guess < random_int:
print("That guess is too low!")
if guess > random_int:
print("That guess is too high")
print("It took you ", len(past_guesses), " guess(es) to guess the number")
print("Your previous guess(es) were: ", past_guesses)
def values():
''' This function asks for inputs to then use to generate a random number from'''
low_val = int(input("Please enter a lower value"))
high_val = int(input("Please enter a higher value"))
random_int = random.randint(low_val, high_val)
guesses(random_int)
values()
| true |
0a6bbd38acc8d8d6fef6e0df7767295bdee15dab | gabrielx52/data-structures | /src/linked_list.py | 2,833 | 4.25 | 4 | """Singly linked list data structure."""
class Node(object):
"""Make node object class."""
def __init__(self):
"""Make node object class."""
self.data = None
self.next = None
class LinkedList(object):
"""Make linked list class."""
def __init__(self, iterable=()):
"""Make linked list object."""
self.head = None
self._count = 0
if isinstance(iterable, (str, tuple, list)):
for item in iterable:
self.push(item)
def push(self, val):
"""Push a new node on head of linked list."""
new_node = Node()
new_node.data = val
new_node.next = self.head
self.head = new_node
self._count += 1
def pop(self):
"""Remove and return the head item of linked list."""
if not self.head:
raise IndexError('Cannot pop from empty list.')
pop_node = self.head
self.head = pop_node.next
self._count -= 1
return pop_node.data
def size(self):
"""Return size of linked list."""
return self._count
def __len__(self):
"""Return length of linked list with len function."""
return self._count
def search(self, val):
"""Return node containing value in list if present otherwise None."""
current_node = self.head
while current_node:
if current_node.data == val:
return current_node
current_node = current_node.next
return
def remove(self, node):
"""Remove node from linked list."""
previous_node = None
current_node = self.head
while current_node:
if current_node == node:
if previous_node:
previous_node.next = current_node.next
current_node.next = None
self._count -= 1
else:
current_node.next = None
self._count -= 1
previous_node = current_node
current_node = previous_node.next
return
def display(self):
"""Display the linked list value as if a tuple."""
display_string = ""
current_head = self.head
while current_head:
display_string = "'" + str(current_head.data) + "', " + display_string
current_head = current_head.next
return "(" + display_string[:-2] + ")"
def __str__(self):
"""Print the display."""
return self.display()
def ll_pal(ll):
"""."""
hold = []
curr = ll.head
while curr:
hold.append(curr.data)
curr = curr.next
mid = len(ll) // 2
left, right = hold[:mid], hold[mid:]
if len(right) > len(left):
right = right[1:]
return left == right[::-1]
| true |
18b55d65fbf145e4e0bf205256f78fa3a3124b21 | Vich3rlys/python-game | /physics/vector.py | 443 | 4.125 | 4 | """class 'physics.Vector' used to handle two-dimensional positions and vectors"""
class Vector ():
def __init__(self,x,y):
self.x,self.y = x,y
def __add__(self,vector):
return Vector(self.x+vector.x , self.y+vector.y)
def __sub__(self,vector):
return Vector(self.x-vector.x , self.y-vector.y)
def __mul__(self,vector):
return Vector(self.x*vector.x, self.y*vector.y)
def __str__(self):
return "("+str(self.x)+","+str(self.y)+")" | false |
724bd78b764cc90ea1e5be3c89d9abc4dc950ab4 | PedroRamos360/PythonCourseUdemy | /kivy/aulas/Seção 13 - Strings/ComparandoString.py | 269 | 4.1875 | 4 | # baseado na Tabela ASCII
print('a' > "X") # True
print('a' > '1') # True
print('a' > '9') # True
print(chr(100)) # Retorna a String respectivo ao código
print(ord("d")) # Retorna o código respectivo a String
for c in range(123):
print(str(c) + ' - ' + chr(c))
| false |
b7c55bd7a6294ad053ab627ab6ce36bb83bca356 | patelmanish1994/basicprograms | /fabnocci.py | 365 | 4.21875 | 4 |
number1=input("enter the first number series : ")
number2=input("enter the second number series : ")
number_of_terms=input("enter the number of terms required : ")
print number1
print number2
while (number_of_terms!=0):
num3=number1+number2
number1=number2
number2=num3
number_of_terms=number_of_terms-1
print num3
| true |
429f0adb0dd9fda7f471363c39ac23511ceb7408 | TejasMorbagal/Deep-Learning | /Assingment01/hw1_linear.py | 2,028 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on
@author: fame
"""
import numpy as np
from matplotlib import pyplot as plt
def predict(X,W,b):
"""
implement the function h(x, W, b) here
X: N-by-D array of training data
W: D dimensional array of weights
b: scalar bias
Should return a N dimensional array
"""
return sigmoid(np.dot(X, W) + b)
def sigmoid(a):
"""
implement the sigmoid here
a: N dimensional numpy array
Should return a N dimensional array
"""
"""for values in a:
sig_a = 1 / (1 + math.exp(-a))
return sig_a """
return 1/(1+np.exp(-a))
def l2loss(X,y,W,b):
"""
implement the L2 loss function
X: N-by-D array of training data
y: N dimensional numpy array of labels
W: D dimensional array of weights
b: scalar bias
Should return three variables: (i) the l2 loss: scalar, (ii) the gradient with respect to W, (iii) the gradient with respect to b
"""
pred = predict(X, W, b)
l2 = np.sum(np.square(y-pred))
gradE_pred = y - pred
gradE_h = gradE_pred*pred*(1-pred)
gradE_h = gradE_h.reshape((gradE_h.shape[0],1))
gradE_W = np.mean((-2*X)*gradE_h, axis=0)
gradE_b = np.mean(-2*gradE_h, axis=0)
return l2, gradE_W, gradE_b
def train(X,y,W,b, num_iters=1000, eta=0.001):
"""
implement the gradient descent here
X: N-by-D array of training data
y: N dimensional numpy array of labels
W: D dimensional array of weights
b: scalar bias
num_iters: (optional) number of steps to take when optimizing
eta: (optional) the stepsize for the gradient descent
Should return the final values of W and b
"""
loss = []
eta = 1
for i in range(num_iters):
l2, gradE_W, gradE_b = l2loss(X, y, W, b)
W = W - eta*gradE_W
b = b - eta*gradE_b
loss.append(l2)
plt.plot(range(num_iters), loss)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.show()
return W, b
| true |
d60dc8ed8df6c1c35478f2bd5a786ebb514965c4 | HLanZZZ/TestPY1 | /test4.py | 729 | 4.21875 | 4 | # 练习使用list
classmates = ['laozhu', 'huazai', 'laoluo']
print(classmates[-1])
classmates.append('conger')
print(classmates)
classmates.reverse()
print(classmates)
classmates.remove('laozhu')
print(classmates)
classmates.insert(3, 'laozhu')
print(classmates)
# 要删除指定位置的元素可以通过使用pop(i)方法pop()默认删除最后一个元素
classmates.pop()
print(classmates)
# list里面的元素也可以不同
L = ['laozhu', 22, 174.8, True]
# list中元素也可以是list
l = ['laozhu', 22, ['huazai', 12], 10.2]
# 另外还有一种有序列表叫元组 -- tuple -- tuple和list非常相似,区别在于tuple里面的元素不可变
classmates2 = ('laozhu', 'laozhang', 'huazai', 'luoyong')
| false |
b114f3d71ebdae2a74750a2f0d56ad7bd8da3155 | bigdata202005/PythonProject | /Day06/8_Q10.py | 703 | 4.28125 | 4 | """
Q10 사칙연산 계산기
다음과 같이 동작하는 클래스 Calculator를 작성하시오.
cal1 = Calculator([1,2,3,4,5])
cal1.sum() # 합계
15
cal1.avg() # 평균
3.0
cal2 = Calculator([6,7,8,9,10])
cal2.sum() # 합계
40
cal2.avg() # 평균
8.0
"""
class Calculator:
def __init__(self, data_list):
self.data_list = data_list
def sum(self):
print(sum(self.data_list))
def avg(self):
print(round(sum(self.data_list) / len(self.data_list), 1))
if __name__ == '__main__':
cal1 = Calculator([1, 2, 3, 4, 5])
cal1.sum() # 합계
cal1.avg() # 평균
cal2 = Calculator([6, 7, 8, 9, 10])
cal2.sum() # 합계
cal2.avg() # 평균 | false |
c11cbfd681b51f2570f462dc41bf90683c2efe17 | crusteoct/Business_tools | /2020.02.18_VAT_yes-or-no.py | 1,490 | 4.40625 | 4 | # VAT in the EUROPEAN UNION. One country must be from the EU for this program to have proper functionality.
# More complex functions can be added, like invoicing of goods, where the invoice from and ship from countries differ.
country_list_eu = [
'bulgaria',
'croatia',
'cyprus',
'czech republic',
'denmark',
'estonia',
'finland',
'france',
'germany',
'greece',
'hungary',
'ireland',
'italy',
'latvia',
'lithuania',
'luxembourg',
'malta',
'netherlands',
'poland',
'portugal',
'romania',
'slovakia',
'slovenia',
'spain',
'sweden',
]
invoicing_from = input('Where are you invoicing from? Enter EU Country: ').lower()
invoicing_to = input('Where are you invoicing to?(customer). Enter Country: ').lower()
eu_validvatnr = ''
if invoicing_from in country_list_eu and invoicing_to not in country_list_eu:
print('No VAT applies, keep export declaration.')
if invoicing_from == invoicing_to:
print(invoicing_from.upper() + ' VAT applies.')
if invoicing_from in country_list_eu and invoicing_to in country_list_eu:
eu_validvatnr = input('Does the customer have a valid EU VAT number?(enter yes or no): ').lower()
if eu_validvatnr == 'yes':
print('No VAT applies.')
else:
print(invoicing_from.upper() + ' VAT applies.')
if invoicing_from and invoicing_to not in country_list_eu:
print('This program requires for at least one item to be an EU Country.')
| true |
0e42cce8e8849d2ea148490a68dabd7ccfc25ef1 | ryanjvice/Python-Bible-Homework | /baby talk.py | 499 | 4.1875 | 4 | #generate random question
#allow person to attempt an answer
#as long as answer isn't "just because," keep asking, "but why?"
#once "just because" is answered, ask another question, forever
while True:
from random import choice
question = ["Why is the sky blue?: ", "Why don't the stars fall?: ", "Where does the sun go?: ".strip().lower()]
answer = input(choice(question))
while answer != "just because".strip().lower():
answer = input("...but why? ")
| true |
666803c2fcf2a40fcf2b897af6d3b8d69a222130 | Poli75D/Python-basics | /CLASS - Vehicle.py | 1,782 | 4.28125 | 4 | #define a class
class Vehicle:#(object):
speed = 0
#def __new__(cls):
# return object.__new__(cls)
def __init__(self, speed = 2): #wartość domyślna prędkości pojazdu
self.speed = speed
def IncreaseSpeed(self, increaseAmount):#funkcja speed1
self.speed += increaseAmount
def __add__(self, otherVehicle): #?Overloading operators
return Vehicle(self.speed + otherVehicle.speed)
def __del__(self):#zwróci komunikat przy usunięciu obiektu
print("Object has been destroyed")
class Car(Vehicle):#definiowanie klasy 'Car' z dziedziczeniem funkcji z klasy 'Vehicle'
weight = 1000
def IncreaseWeight(self, weight): #nowa funkcja tylko dla obiektów z klasy 'Car'
self.weight += weight
def IncreaseSpeed(self, increaseAmount):#funkcja speed2, przy dziedziczeniu funkcji, jeżeli w podklasie zdefiniujemy tę samą funkcję w inny sposób, nadpisuje ona funkcję nadklasy w tym konkretnym obiekcie klasy
self.speed *= increaseAmount
#add objects to class
car1 = Vehicle() #wygeneruje wartość domyślną
car2 = Vehicle(345) #zmienia wartość domyślną na danym pojeździe
car3 = Vehicle(0)
car4 = Car(20)
car5 = car1+car2
#access attributes
print(car4.weight)
car4.IncreaseWeight(100)
print(car4.weight)
car4.IncreaseSpeed(5)
print(car4.speed)
print("Speed of car 1: %i" % car1.speed)
print("Speed of car 2: %i" % car2.speed)
print("Speed of car 3: %i" % car3.speed)
car1.IncreaseSpeed(5)
car2.IncreaseSpeed(-100)
print("Speed of car 1: %i" % car1.speed)
print("Speed of car 2: %i" % car2.speed)
#print("Speed of car 3: %i" % car3.speed)
car5.IncreaseSpeed(7)
print("Speed of car 5: %i" % car5.speed)
del car3
| false |
2c2aa206ca145ef633d340f9cc18f9a91ae66776 | joabefs/python-stuff | /dateConvert.py | 538 | 4.25 | 4 | # dateConvert - convert dates to strrings
from string import split
def main():
print "dateConvert, convert a date to a string"
print
monthStr, dateStr, yearStr = split(raw_input("Enter date (mm/dd/YYYY): "),"/")
months = ["January","February","March","April","May","June","July","August","September","October",
"November","December"]
#print "The date entered:", months[int(monthStr)-1], dateStr+",", yearStr
print "The date entered: %s %s, %s" % (months[int(monthStr)-1], dateStr, yearStr)
main()
| true |
d778559ac59cfa1f9c5112ed4d246439984f6797 | manimaran-elumalai/Giraffe_Academy_Python | /functions.py | 905 | 4.15625 | 4 | #function is a collection of codes which performs a specific task
#it allows to organize a code in a better way and allows to break the code
def say_hi(): #when def is used it will create a funtion type and all the codes keyed in will be stored under this.
print("Hello " + input("please enter your name: ")) #this code will not be executed automatically until it is called separetely.
print("Beginning")
say_hi()
print("Ending")
#parameter is a piece of information given to functions that are being created.
def say_hello(name, age): #here name & age is the parameter and you can assign as many parameters you want to
print("Hello " + name + ", you're " + age + " years old.")
say_hello("Mani", "43")
say_hello("Mohan", "43")
def say_hello1 (name, age):
print("Hello " + name + ", you're " + str(age) + " years old.") #here we're converting the int (age) to a str
say_hello1("David", 18) | true |
67246f4739e462aee2ca27b6e3a15debd71c1b78 | KRLoyd/holbertonschool-higher_level_programming | /original_repo/0x06-python-test_driven_development/2-matrix_divided.py | 1,330 | 4.1875 | 4 | #!/usr/bin/python3
def matrix_divided(matrix, div):
"""
Divides all elements of a matrix.
Args:
matrix -- matrix to evaluate
div -- number to divide matrix elements by
Return: new matrix with the result of division
"""
# Check if div is 0
if div == 0:
raise ZeroDivisionError("division by zero")
# Check if div is int or float
if isinstance(div, (int, float)) is False:
raise TypeError("div must be a number")
# Check that each row of matrix is the same size
row_len = len(matrix[0])
for row in matrix:
if len(row) != row_len:
raise TypeError("Each row of the matrix must have the same size")
# Create new_matrix
new_matrix = []
# Iterate through the matrix rows and elements to
# check if element is not int or float
for row in matrix:
for element in row:
if isinstance(element, (int, float)) is False:
raise TypeError("matrix must be a "
"matrix (list of lists) of integers/floats")
# Iterate through the matrix rows
for row in matrix:
# make new row with division
new_row = list(map(lambda x: round((x / div), 2), row))
# append new_row to new_matrix
new_matrix.append(new_row)
return new_matrix
| true |
a443bf5dea0857a64283f04f2364487b7431789e | KRLoyd/holbertonschool-higher_level_programming | /original_repo/0x03-python-data_structures/10-divisible_by_2.py | 492 | 4.4375 | 4 | #!/usr/bin/python3
def divisible_by_2(my_list=[]):
""" My function that finds all multiples of 2 in a list
Arg: list to evaluate
Return: list with "True" or "False" depending on if the integer at that
same position in the original list is a multiple of 2.
"""
result_list = []
for i in my_list:
if i % 2 is 0:
result_list.append(True)
else: # integer isn't divisible by 2
result_list.append(False)
return result_list
| true |
2ea8432142ad5d88c8c50fc1d12e66bc24591145 | KRLoyd/holbertonschool-higher_level_programming | /original_repo/0x03-python-data_structures/5-no_c.py | 348 | 4.28125 | 4 | #!/usr/bin/python3
def no_c(my_string):
""" My function that removes all characters c and C from a string.
Arg: string to evaluate
Return: new string
"""
new_string = ""
for i in range(0, len(my_string)):
if my_string[i] != 'c' and my_string[i] != 'C':
new_string += my_string[i]
return new_string
| true |
08701f3f9512c0126bb7b2903ad6433e83b62406 | KRLoyd/holbertonschool-higher_level_programming | /original_repo/0x0A-python-inheritance/my_mains/main-3.py | 1,184 | 4.125 | 4 | #!/usr/bin/python3
is_kind_of_class = __import__('3-is_kind_of_class').is_kind_of_class
a = 1
if is_kind_of_class(a, int):
print("{} comes from {}".format(a, int.__name__))
if is_kind_of_class(a, float):
print("{} comes from {}".format(a, float.__name__))
if is_kind_of_class(a, object):
print("{} comes from {}".format(a, object.__name__))
print()
a = 'ah'
if is_kind_of_class(a, str):
print("{} comes from {}".format(a, str.__name__))
if is_kind_of_class(a, float):
print("{} comes from {}".format(a, float.__name__))
if is_kind_of_class(a, object):
print("{} comes from {}".format(a, object.__name__))
print()
a = 8.7
if is_kind_of_class(a, int):
print("{} comes from {}".format(a, int.__name__))
if is_kind_of_class(a, float):
print("{} comes from {}".format(a, float.__name__))
if is_kind_of_class(a, object):
print("{} comes from {}".format(a, object.__name__))
print()
a = [2, 3]
if is_kind_of_class(a, int):
print("{} comes from {}".format(a, int.__name__))
if is_kind_of_class(a, list):
print("{} comes from {}".format(a, list.__name__))
if is_kind_of_class(a, object):
print("{} comes from {}".format(a, object.__name__))
| false |
3a3bc74d0da9701459808516d417892ec935a21b | KRLoyd/holbertonschool-higher_level_programming | /original_repo/0x0A-python-inheritance/11-square.py | 756 | 4.4375 | 4 | #!/usr/bin/python3
"""method to define class Square"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""Square Class"""
def __init__(self, size):
"""method __init__
Instantiation of size.
"""
super().integer_validator("size", size)
self.__size = size
Rectangle.__init__(self, size, size)
self.__width = size
self.__height = size
def __str__(self):
"""method __str__
Prints square description in the following format:
[Square] <width>/<height>
"""
sq_width = str(self.__width)
sq_height = str(self.__height)
sq_return = "" + "[Square] " + sq_width + "/" + sq_height
return sq_return
| true |
17548c5647233e5c71b46d7c93ca172672027247 | kev1991/PLatzi_Curso_Basico_Python | /Curso Básico de Python/Conversor.py | 652 | 4.25 | 4 | def converter (type_pesos, dollar_value):
pesos = input("How many "+ type_pesos + " pesos do you have?: ")
pesos = float(pesos)
dollars = pesos / dollar_value
dollars = round(dollars, 2)
dollars = str(dollars)
print ("You have $" + dollars + " dollars")
menu = """
Welcome to currency converter 💲
#1 Colombian pesos
#2 Argentine pesos
#3 Mexican pesos
Choose an option:
"""
option = input(menu)
if option == "1":
converter ("Colombias", 3875)
elif option == "2":
converter ("Argentine", 65)
elif option == "3":
converter ("Mexican", 24)
else:
print("Please enter one correct option ") | true |
b6325a3b1f2fc292739d6279999de3918305bc06 | stomaras/Machine-Learning | /DataPreprocessing/DataFrames/DataFramesIterate.py | 863 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 13:07:44 2020
@author: sptom
"""
import pandas as pd
import numpy as np
df = pd.DataFrame()
Name = ['Mr Virat Kohli','Mrs Susan Whisler','Mr Michael Scofield','Mrs Sarah Wilson']
Sex = ['Male','Female','Male','Female']
ID = [1001,1002,1003,1004]
Country = ['India','Australia','England','Canada']
df['Name'] = Name
df['ID'] = ID
df['Sex'] = Sex
df['Country'] = Country
for name in df['Name']:
print(name)
# Print Name Column with uppercase
for name in df['Name']:
print(name.upper())
for name in df['Name'][0:3]:
print(name.upper())
# Now if we want to add the Column with the Uppercase we do the follow steps
df['Upper_case'] = df['Name'].apply(lambda x: x.upper())
# Now if we want to print all columns one by one we do the follow steps
for column in df:
print(df[column])
| false |
e46707b110d6efb81adb4b5ecb799358001ee0df | vivekpython01/vivek_py | /Day3.py | 1,453 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[17]:
# Adding Whitespace to the string
print('python')
print('\tpython')
print("hello\t...")
# Note : "\t" is a tab,
# "\n" is a newline
# In[15]:
print("languages:\n\tpython\n\tjava\n\tswift\n\truby")
# In[39]:
print('Hello, \'friend\'!Please enter your name below:Name:(your name here)Age:(your age here)')
print("\n")
print('Hello, \'friend\'!\nPlease enter your name below:\nName:\t(your name here)\nAge:\t(your age here)')
print("\n")
print('Here\'s how you print directories path: \"C:Users\\python\\examples\"')
#Note :
print("\\ => print Backslash (\)")
print("\' => Single quote (')")
print('\" => Double quote (")')
#Note :\\ Backslash (\)
# \' Single quote (')
# \" Double quote (")
# In[60]:
# How to remove whitespace
fav_lang1 ="Python " # rightside space
fav_lang2 =" Java" # rightside space
fav_lang3 =" MongoDB " # space both side
print(fav_lang1)
print(fav_lang2)
print("-------output after removing space---------")
print(fav_lang1.rstrip())
print(fav_lang2.lstrip())
print(fav_lang3.strip())
# In[49]:
# Number
2+3 # Addition of integer
# In[48]:
3-5 #Subtraction of integer
# In[50]:
2*5 #Multiplication of integer
# In[51]:
20/5 #Division of integer
# In[52]:
2**3 # 2 to the Power 3
# In[53]:
# float
3.0+4.1
# In[56]:
x = 2.1
y = 3.1
# In[58]:
z=x+y
print(z)
# In[59]:
type(z)
| false |
3193cfc3d8efafcbdfd5e0fc1efc1dd99de6c91a | Nihal-prog/Calendar-in-python | /main.py | 584 | 4.1875 | 4 | # Calender Program
# Importing modules
import calendar
import datetime
# Introduction To The Program
print("\n\t\t\t$$$$$$$$$$$$$$$ Calendar Printing Program $$$$$$$$$$$$$$$\n")
date = datetime.datetime.now()
x = date.strftime("%d-%m-%y")
print(f"Date of Execution: {x}\n")
# Taking User Inputs
year = int(input("Enter the year you want the calendar of: "))
month = int(input("Enter the month you want: "))
# Printing Calendar
print("\nHere's Your Calendar")
print("###########################\n")
cal = calendar.month(year, month)
print(cal)
print("###########################")
| true |
374b8b173aa4665209b36627977873f1a5e3ab42 | ProgFuncionalReactivaoct19-feb20/clase03-andresvallejoz1991 | /Ejercicion1.py | 489 | 4.15625 | 4 | """
andresvallejoz1991
"""
#Funcion
def palindromas(x):
lista = ["oro","ojo","oso","radar","seres"]#palabras palindromas
if x in reversed (lista):#Condiconal para la reversa
return True
else:
return False
#Listado de las palabras
datos = ["oro","pais","ojo","oso","radar","sol","seres"]
resultado = filter(lambda x: x == "".join(reversed (x)),datos)#Condicional Lambda
#Filtra las palabras que son iguales al derecho y al reves
print(list(resultado))#Impresion resultado
| false |
68514cdbd874aaa839d0267ac57c14acacdd04c1 | rsmetana/Python | /venv/100_days_of_python/Day3/cont_flow_if_else.py | 385 | 4.40625 | 4 | #if condition:
# do this
#else:
# do this
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print('You can ride this rollercoaster!')
else:
print('Sorry you need to grow a bit.')
#Comparison Operators
#> greater than
#< less than
#>= greater than or equal to
#<= less than or equel to
#== equal to
#!= not equal to
| true |
81299dce751f7b1ab43fa0e2a2216f7531dc7413 | DavidCorzo/2.2 | /___Algoritmia_y_Complejidad-Notas___/proyecto/binary_sort.py | 859 | 4.1875 | 4 | from math import floor
def binary_search(array, value, start, end):
# Base cases.
if (start == end):
if (array[start] > value):
return (start)
else:
return (start + 1)
if (start > end):
return (start)
middle = floor((start+end)/2)
# Recursion conditions.
if (array[middle] < value):
return binary_search(array, value, middle+1, end)
elif (array[middle] > value):
return binary_search(array, value, start, middle-1)
else:
return (middle)
def insertion_sort(array):
for i in range(1, len(array)):
value = array[i]
j = binary_search(array, value, 0, i-1)
array = array[:j] + [value] + array[j:i] + array[i + 1:]
return array
array = [100, 5, 2, 32, 10005, 69, 88, 1]
print("Result:")
print (insertion_sort(array))
| true |
beb7b8cfa55607114b67b519018e1903c3811acc | chauhanmahavir/Python-Basics | /convert to binary.py | 224 | 4.15625 | 4 | def convertToBinary(n):
# Function to print binary number for the input decimal using recursion
if n > 1:
convertToBinary(n//2)
print(n % 2,end = '')
# decimal number
dec = 0
convertToBinary(dec)
| true |
75c72223430db5cbe4c13b37d960750021416783 | chauhanmahavir/Python-Basics | /List_manupulation.py | 714 | 4.1875 | 4 | x = [2,3,5,2,4,6,4]
'''Apend at last position
append(value)'''
x.append(2)
print(x)
'''Insert(index,value)'''
x.insert(2,99)
print(x)
'''remove(value)
remove first value)'''
x.remove(2)
print(x)
'''remove at index 2'''
x.remove(x[2])
print(x)
'''print(x[start:stop])
It will print form start index to stop-1 index'''
print(x[3:6])
'''print last element of list'''
print(x[-1])
'''print last second element of list'''
print(x[-2])
'''print index of value
print index of value 4'''
print(x.index(4))
'''count the spacific value in list'''
print(x.count(4))
'''sort the element of list'''
x.sort()
print(x)
y=['Jan','jone','bob','jan']
y.sort()
print(y)
| true |
6e98da8ba8cf71b0a102aa90ffb16ebfca05e443 | doomnonius/codeclass | /week-6/data-structures.py | 2,488 | 4.25 | 4 | # linked list
class Node:
def __init__(self, data, next=None, previous=None):
""" The next variable will represent the next item in our list, and we can go down the list until we have a none.
"""
self.data = data
self.next = next
self.previous = previous #This is used in a doubly linked list
# python has a generic list type, has append, indexing into list
# uses a dynamic array, extending memory automatically when you get to the end
# actually puts pointers into the list to ensure each item in the list is the same size
# stack: data structure with LIFO, add and remove only from the top, practically speaking moves pointer up and down the data array
# stacks are done using a list
# queues: FIFO, keep track of start and back of the list
# in python to use queues, from collection import deque
# trees: sort of like linked lists, but nodes can point to multiple other nodes on the same tree
# binary tree: common subtype, always 0-2 children, right and left
class NodeTree:
def __init__(self, data, right, left):
""" Everything on a tree structure ends up being O(log n), how many elements you need to go down grows with the log of the length.
"""
self.data = data
self.right = right
self.left = left
def __repr__(self):
s = ' '
if self.right != None:
s += print(self.right) + ', '
s += self.data + ', '
if self.left != None:
s += print(self.left) + ', '
return s
# Exercise: print numbers in a tree in order. Assume right tree is larger and left tree is smaller.
def printacc(node):
try:
if node.right != None:
printacc(node.right)
except:
pass
print(node.data)
try:
if node.left != None:
printacc(node.right)
except:
pass
d = NodeTree(8, 10, NodeTree(5, None, 2))
printacc(d)
print(d.left.left)
# a graph is like a tree, but any element can point to any other element, no limitations
# hash/hashmap/dictionary: if we have a bunch of elements we want to link, goal is to spread out data,
# hash function: work in constant time, as do hash lookups
L = [1, 9, 3, 6, 2]
k = 13
def twoEqK(L, k):
""" Takes a list and checks if any two elements in the list add up to k.
"""
dictionary = {}
for i in L:
if k - i in dictionary:
return True
dictionary[i] = None
return False
print(twoEqK(L, k))
| true |
4b7cca79aacc0c60d4a61b3f643343a8cdb9f5af | ARN0LD-2019/Ejercicios_Python_2020 | /unidad2/ejercicio3.py | 746 | 4.28125 | 4 | #realiza un programa que cumpla el siguiente algoritmo utilizando siempre que
# sea posible operadores de asignacion
# guardar en una variable numero_magico 12345679 (sin el 8)
# lee por pantalla otro numero_usuario especifica que sea entre 1 y 9
# multiplica el numero_usuario por 9 en si mismo
# multiplica el numero magico por el numero usuario en si mismo
# finalmente muestra el valor final del numero_magico por pantalla
numero_magico = 12345679
numero_usuario = int(input(" introduce un numero: "))
numero_usuario = numero_usuario * 9
print("el numero usuario multiplicado por 9 es: ", numero_usuario)
numero_magico = numero_usuario * numero_magico
print ("el numero magico multiplicado por el numero usuario es :", numero_magico) | false |
861e0e249662d0e0b42127a0447e4c96fc77b1ec | ARN0LD-2019/Ejercicios_Python_2020 | /unidad2/ejercicio1.py | 620 | 4.28125 | 4 | # Realiza un programa que lea dos numeros por teclado y determine los siguientes aspectos (es suficiente con
# mostrar true or false)
#si los dos numeros son iguales
#si los dos numeros son diferentes
#si el primero es mayor que el segundo
#si el segundo es mayor o igual que el primero
n1 = float(input("introduce el primer numero: "))
n2 = float(input("introduce el segundo numero: "))
print("los numeros son iguales ?", n1 == n2 )
print("si los dos numeros son diferentes? ", n1 != n2)
print("si el primero es mayor que el segundo ?", n1 > n2)
print("si el segundo es mayor o igual que el primero? ", n2 >= n1) | false |
73f116578729d7b2a22c144d5560443c2ef8dd35 | ARN0LD-2019/Ejercicios_Python_2020 | /unidad10/ejercicio2.py | 535 | 4.28125 | 4 | # se puede generar una lista desde la siguiente estructura
lista = [1, 2, 3, 4, 5]
print(lista)
lista.append(6)
print(lista)
# el metodo count te muestra la cantidad x de elementos en tu lista
lista2 = ["hola mundo", "hola marte", "hola jupiter", "hola saturno"].count(
"hola mundo"
)
print(lista2)
# metodo index te muestra el primer elemento de tu lista
lista3 = ["hola mundo", "hola marte", "hola jupiter", "hola saturno"].index(
"hola jupiter"
)
print(lista3)
lista4 = list("hola mundo")
lista4.reverse()
print(lista4)
| false |
985b29193747b3aa295e8cd54da3d20d9c080f14 | viperk17/Practice_with_python3 | /18.Decorators.py | 1,850 | 4.46875 | 4 | # Decorators : Dynamically Alter the functionality of the function
'''
first class functions allow us to treat functions like any other objects
We can pass functions as arguments to other functions. Closure allows us
to take advantage of first class function and return inner function that
remember and has access var local to the scope in which they were created
'''
# def outer_function():
# message = 'Hi'
from orca.sound import args
'''
def outer_function(msg):
message = msg
def inner_function(): # inner function has access to var message
print(msg)
return inner_function()
hi_func = outer_function('Hi')
bye_func = outer_function('Bye')
hi_func
bye_func
'''
'''
Decorator is a function that takes another function as an argument, adds some functionality
and returns another functions without altering the source code
'''
def decorator_function(origional_function):
def wrapper_function(*args, **kwargs): # inner function has access to var message
print('wrapper executed this before {}'.format(origional_function.__name__))
return origional_function(*args, **kwargs)
return wrapper_function
# #Using class
# class decorator_class(object):
# def __init__(self, origional_function):
# self.origional_function = origional_function
#
# def __call__(self, *args, **kwargs):
# print('call method executed this before {}'.format(self.origional_function.__name__))
# return self.origional_function(*args, **kwargs)
@decorator_function # for class use - @decorator_class
def display():
print('Display function ran...')
# decorated_display = decorator_function(display)
# decorated_display()
@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))
display_info('Josh', 28)
display()
| true |
83cded15c2854ff21f8eff62e6c34e975bde7a06 | viperk17/Practice_with_python3 | /4. List Comprehensions.py | 2,029 | 4.28125 | 4 | # list1 = [2, 5, 'June']
# list1.insert(1, 1)
# print(list1)
#
# # list1.remove(1)
# # print(list1)
#
# list1.append(['alpha','echo'])
# print(list1)
#
# list1.extend(['alpha','brao','charlie'])
# print(list1)
#
# # lst = list1.sort()
# # print(lst)
#
# # list1.pop(-1)
# # print(list1)
#
# list1.reverse()
# print(list1)
#
# courses = ['English','Math','Physics','CS']
# print(len(courses))
# try:
# print(courses[4])
# except:
# print("Not in range")
#
# courses.append('Art')
# print(courses)
#
# courses.insert(1,'Chemistry')
# print(courses)
#
# courses2 = ['Hindi','Education']
# courses.append(courses2)
# print(courses)
#
# courses.extend(courses2)
# print(courses)
#
# courses.remove(courses2)
# print(courses)
#
# courses.pop()
# print(courses)
#
# courses.reverse()
# print(courses)
#
# courses.sort(reverse=True)
# print(courses, "Using Reverse")
#
# # Sorting without using .sort()
#
#
# # while courses:
# # min = courses[0] # arbitrary in list
# # for x in courses:
# # if x > min:
# # min = x
# # new_list.append(min)
# # courses.remove(min)
# print(new_list)
# ################## sorting end ####################################
#
# sorted_courses = sorted(courses)
# print(sorted_courses)
#
# # find the index of element
# print(courses.index("English"))
#
# # for course in courses:
# # print(course)
#
# for index, course in enumerate(courses, start=101):
# print(index, course)
#
# # join the elements of the list
# course_str = ' <-> '.join(courses)
# print(course_str)
#
# # to reverse the change, split values
# n_list = course_str.split(" <-> ")
# print(course_str)
# print(n_list)
# # Working with Tuples
# tuple1 = ('History','Math','Physics','Java')
# tuple2 = tuple1
# print(tuple1)
# print(tuple2)
# try:
# tuple1[0] = 'Art'
# except Exception as e:
# print(e)
# Working with Sets
# cs_courses = {'History','Math','Physics','CS','Math'}
# art_courses = {'History','Math','Art','Design'}
# print(cs_courses.union(art_courses))
| false |
ff2b35ebc529791bfb6308bf3ccf11993d19cd48 | yojimbo88/ICTPRG-Python | /w5q4.py | 466 | 4.15625 | 4 | name = input("Enter your name: ") # user input variable for name.
name2 = name.split(" ") # split string into a list split by " " (space).
initials = ""
for i in range(len(name2)): # loop that takes the first letter of each part of the name.
name = name2[i]
initials = initials + name[0].upper() # this the first letter of each word and makes it upper case.
print("Initials: ", initials)
# Tomas Franco 101399521 | true |
f358352fda5a5f8ed834c0bedf53e534f1d0176e | yojimbo88/ICTPRG-Python | /challenge (Tomas Franco 101399521).py | 1,384 | 4.40625 | 4 | # introduction/instructions.
print("Input Details")
# loop requesting user to input details, loop will break if user leaves it blank in any instance.
while True:
first_name = input("First name: ")
if first_name == "":
print("First name left blank.")
break
last_name = input("Last name: ")
if last_name == "":
print("Last name left blank.")
break
age = input("Age: ")
if age == "":
print("Age left blank.")
break
# variable introducing ID number as a list of string.
student_id = list(str(101399521))
# variable introducing the 3rd to last digit of ID number.
id_3rd_last = int(student_id[-3])
# variable below offsetting the user's age by the 3rd to last digit of ID number.
year = 2021 - int(age)
year_output = year - id_3rd_last
# variables converting the user's input into a list.
first_letter = list(first_name)
first_letter2 = list(last_name)
# variable that will determine the user's domain as a string.
email = "@Huawow.io"
# output the combination of first letter of name and surname as well as password (name and upper case first letter of surname) in the same line separated by "|".
print(first_letter[0].lower() + last_name.lower() + email, end="|")
print(first_name.lower() + first_letter2[0].upper() + "_" + str(year_output))
# Tomas Franco 101399521. | true |
c0a50258065dcc33d30e338dabf01ef836a8e62c | mukhaimy/PythonTutorialP1 | /Soal01.py | 764 | 4.15625 | 4 | '''
Create a program that asks the user to enter their
name and their age. Print out a message addressed to
them that tells them the year that
they will turn 100 years old.
GT:
Buat program yang meminta pengguna untuk
memasukkan nama dan usia mereka.
Cetak pesan yang ditujukan kepada mereka
yang memberi tahu mereka tahun di mana mereka
akan menginjak usia 100 tahun.
'''
tahunSekarang = 2040
nama = input('Masukkan Nama Anda: ')
umur = input('Umur Anda: ')
# karena fungsi [input] menghasilkan variabel bertipe "string"
# maka perlu dikonversi ke integer
umur = int(umur)
menuju100 = 100 - umur
ultah100 = tahunSekarang + menuju100
print("Hallo, ", nama, \
" akan berulang tahun ke-100 pada tahun:", \
ultah100) | false |
97248201c0ad7e2e4883b644d9769b33c2ada559 | mukhaimy/PythonTutorialP1 | /Soal06.py | 492 | 4.15625 | 4 | '''
Ask the user for a string and print out whether
this string is a palindrome or not.
(A palindrome is a string that reads the
same forwards and backwards.)
racecar --> Polindrom
'''
w = input("Masukkan kata uji: ")
nw = len(w)
# apabila huruf besar atau kecil sama saja
# w = w.upper()
polindome = True
for i in range(nw):
if (w[i] != w[nw - 1 - i]):
polindome = False
break
print (w, ' -->> Termasuk Polindrome? ', polindome)
| false |
46abd4254043b9e403c327c37f0cd120442af308 | tymancjo/WhoPy | /01_Welcome/welcome.py | 891 | 4.25 | 4 | import time
class WhoPy:
'''This is a WhoPy class'''
listOfWhoPy =[] #Here we weill memorize all of us!
def __init__(self, myName):
'''This is the initialization function'''
WhoPy.listOfWhoPy.append(self)
self.name = myName
print('badummm... {} was just created!'.format(self.name))
def sayHello(self):
print('Hi! My name is {} and I\'m a python code!'.format(self.name))
# And here is flat code
# Lets create list of names
print('Let\'s create someone!')
names = ['Adam', 'Ewa', 'Zdzich', 'Julia']
# Let's create a WhoPy objects for each name!
for currentName in names:
aNewWhoPyObject = WhoPy(currentName)
time.sleep(1)
# And now let's ask everybody who they are?
print('And now let\'s ask everybody who they are?')
for who in WhoPy.listOfWhoPy:
print('Who are you?')
who.sayHello()
time.sleep(1)
| false |
394ea0705900928abb6b1d558edf118608414a33 | sizanosky/WeatherAroundWorldAPI | /helpers.py | 1,297 | 4.3125 | 4 | def cabecalho():
"""
Função para formatar um cabeçalho para o programa.
:return: string
"""
texto = "Weather around World - Using API by OpenWeather"
print(f'{"=" * len(texto) + 10 * "="}')
print(f'{"*" * len(texto) + 10 * "*"}')
print(f"++++ {texto} ++++")
print(f'{"*" * len(texto) + 10 * "*"}')
print(f'{"=" * len(texto) + 10 * "="}')
def kelvin_para_celsius(temperatura_kelvin):
"""
- Função para converter temperatura de Kelvin para Celsius.
- Formula: (Kelvin) - 273.15
:param temperatura_kelvin: Entrada, temperatura em Kelvin.
:return: Retorna a temperatura em Celsius.
"""
temperatura_celsius = temperatura_kelvin - 273.15
return temperatura_celsius
def valida_saida():
"""
Função para verificar se o usuário deseja continuar executando
o programa.
:return: Entrada do usuário.
"""
while True:
continuar = input("\nDeseja realizar outra pesquisa? [S/N]: ")
if continuar.lower() == 's':
break
elif continuar.lower() == 'n':
print("Encerrando o programa...")
print("Obrigado, até a próxima!!!")
exit(0)
else:
print('OOOPS! Digite "S" para SIM ou "N" para NÃO.')
continue
| false |
4f6db10c58a18209a3665da0ab4e56c4f6dd6640 | LBDM2707/DailyCodingProblem | /30122020-Facebook.py | 1,010 | 4.1875 | 4 | # This problem was asked by Facebook.
# Given a string of round, curly, and square open and closing brackets, return
# whether the brackets are balanced (well-formed).
# For example, given the string "([])[]({})", you should return true.
# Given the string "([)]" or "((()", you should return false.
def check_brackets(s):
queue = []
while len(s) > 0:
ch = s[0]
s = s[1:]
if ch in ["{", "(", "["]:
queue.insert(0, ch)
else:
if len(queue) == 0:
return False
ch2 = queue.pop(0)
if ch == "]" and ch2 != "[":
return False
if ch == "}" and ch2 != "{":
return False
if ch == ")" and ch2 != "(":
return False
return True if len(queue) == 0 else False
print(' Need True = {}'.format(check_brackets("([])[]({})")))
print(' Need False = {}'.format(check_brackets("([)]")))
print(' Need False = {}'.format(check_brackets("((()"))) | true |
0c8db582047dde10c83f9a831b82f764bfe3f56a | ardacancglyn/Python | /12_If_Elif_Else.py | 856 | 4.3125 | 4 | #If-Elif-Else
#Values
x=int(input("Number-1: "))
y=int(input("Number-2: "))
#If-Elif-Else
if x>y:
print("{}>{}".format(x,y))
elif x<y:
print("{}<{}".format(x,y))
else:
print("{}={}".format(y,x))
#Same Code[Just else and elif different]
"""
if x>y:
print("{}>{}".format(x,y))
elif x<y:
print("{}<{}".format(x,y))
elif x==y:
print("{}={}".format(y,x))
"""
#Same Code[Print code different]
"""
if x>y:
print("Number1>Number2")
elif x<y:
print("Number1<Number2")
else:
print("Number1>Number2")
"""
#Odd and Even Number (Simple Example)
a=int(input("Enter a number: "))
if a % 2==0:
print("{} ".format(a) + "Even Number.")
else:
print("{} ".format(a) + "Odd Number.")
| false |
69004416ab5e13041bd319c10666f60fe1295570 | ardacancglyn/Python | /18_Functions.py | 1,250 | 4.1875 | 4 | #Functions
list1=[1,2,3,4,5,2,6,2]
#1-)
print("Append Number or Str Values: ")
list1.append(7)
print(list1)
#2-)
print("Type: ")
print(type(list1))
#3-)
print("How Many Numbers On The List: ")
x=list1.count(2)
print(x)
#4-)
print("Reverse: ")
list2=[10,20,30,40,50,60]
list2.reverse()
print(list2)
#5-)DEF V1 :)
print("Def-1: ")
def addition(a,b):
return a+b
defadd=addition(5,9)
print(defadd)
print(type(addition))
#6-)DEF V2 :)
print("DEF-2: ")
def add(k,l):
print(k+l)
add(1,4)
#7-)DEF V3 :)
print("DEF-3: ")
def information(name,age,gender):
print("""
Name:%s
Age:%s
Gender:%s
""" %(name,age,gender))
information("Joshua","30","Male")
#DEF V4 :)
print("DEF-4: ")
Name=None
Age=None
Gender=None
Name=input("Write Your Name: ")
Age=int(input("Write Your Age: "))
Gender=input("Write Your Gender: ")
print("""
Name:%s
Age:%s
Gender:%s
""" %(Name,Age,Gender))
#DEF V5 :) (Addition)
print("DEF-5(Addition With Def): ")
def function(*args):
additions=0
for i in args:
additions += i
return additions
print(function(1,2,3,4,5,6,7,8,9,10))
| false |
4f170efca8ccbcfc23874ac0f103cd229d3b1634 | JMCSci/Introduction-to-Programming-Using-Python | /Chapter 6/6.5/sortnumbers/SortNumbers.py | 585 | 4.28125 | 4 | ''' Chapter 6.5 '''
def main():
num1, num2, num3 = input("Enter three numbers: ").split(', ');
displaySortedNumbers(num1, num2, num3);
# displaySortedNumbers: Sorts three numbers [works like a bubble sort]
def displaySortedNumbers(num1, num2, num3):
if(num1 > num2):
temp = num2;
num2 = num1;
num1 = temp;
if(num1 > num3):
temp = num3;
num3 = num1;
num1 = temp;
if(num2 > num3):
temp = num3;
num3 = num2;
num2 = temp;
print(num1, num2, num3);
if __name__ == '__main__':
main(); | false |
a5c889140013555abd7aea0c06c71aadb419539e | JMCSci/Introduction-to-Programming-Using-Python | /Chapter 3/3.2/circledistance/GreatCircleDistance.py | 465 | 4.1875 | 4 | ''' Chapter 3.2 '''
from math import sin, radians, acos, cos
RADIUS = 6371.01
x1, y1 = input("Enter point 1 (latitude and longitude) in degrees: ")
x2, y2 = input("Enter point 2 (latitude and longitude) in degrees: ")
# Convert points to radians
x1 = radians(x1)
x2 = radians(x2)
y1 = radians(y1)
y2 = radians(y2)
distance = (RADIUS * acos(sin(x1) * sin(x2) + cos(x1)
* cos(x2) * cos(y1 - y2)))
print "The distance between the two points is", distance, "km" | false |
9aae59631938838413feb22c1146b82ff23514d5 | HAirineo/jissa | /digilog/main.py | 1,723 | 4.125 | 4 | import digilog, math, re
def validate(strg, search=re.compile(r'[1234567890^+-/*]').search):
return not bool(search(strg))
def main():
expr = raw_input("Enter an expression: ")
if validate(expr) == 1:
print("Invalid Input, please enter a valid expression")
main()
try:
base = input("Enter the base of the numbers: ")
except:
print("Invalid Input, please enter a numeric value")
main()
target = input("Enter the target base for the result: ")
print evaluate_expression(expr, base)
print digilog.convert_result(evaluate_expression(expr, base), target)
def decimal_separate(expr):
"Returns the separated whole number and decimal number"
# Decimal number Whole number
return str(math.modf(float(expr))[0]), str(math.modf(float(expr))[1])
def evaluate_expression(expr, base):
"Returns the evaluated expression"
answer = "" # String to contain the answer
regexpr = r'\d+[.]\d+|\d+|[-+/*()]' # Regex determining operators and operands
regexpr_eval = re.findall(regexpr, expr) # Regex method finding all match
for x in range(len(regexpr_eval)):
if regexpr_eval[x] == "+" or regexpr_eval[x] == "-" or regexpr_eval[x] == "*" or regexpr_eval[x] == "/" or regexpr_eval[x] == "(" or regexpr_eval[x] == ")":
# Concatenate the string as it is if it is an operand
answer += regexpr_eval[x]
else:
# Convert the number first before concatenating
answer += str(digilog.decimal_evaluate(decimal_separate(regexpr_eval[x])[0], base) + digilog.whole_evaluate(decimal_separate(regexpr_eval[x])[1], base))
try:
return eval(answer)
except SyntaxError:
return "Syntax Error!"
main()
| true |
877a0e1f99d43e00ffa49fc33e18326bcbdde7c9 | Predstan/Algorithm-and-Data-Structure | /ch8/Queue Using Circular Array/queueArray.py | 1,619 | 4.15625 | 4 | # iMPLEMENTATION OF QUEUE USING CIRCULAR ARRAY
from Array import Array
class Queue:
def __init__(self, numelements):
self.elements = Array(numelements)
self.counts = 0
self.front = 0
self.back = self.front
# Determines if queue is empty
def isEmpty(self):
return self.counts == 0
# Returns the length of items in the Queue
def __len__(self):
return self.counts
# Adds an item to the back of the queue
def enqueue(self, item):
assert self.counts != len(self.elements),\
" Queue is Full"
if self.counts == 0:
self.elements[self.counts] = item
self.front = 0
self.back = 0
self.counts += 1
else:
self.back += 1
self.front = (self.front + 1) % len(self.elements)
self.elements[self.back] = item
self.counts += 1
# Removes an item at the front of the queue
def dequeue(self):
assert not self.isEmpty(), \
"Queue is Empty"
item = self.elements[self.front]
self.elements[self.front] = None
self.front = (self.front + 1) % len(self.elements)
self.counts -= 1
return item
# TEST
hey = Queue(5)
hey.enqueue(9)
hey.enqueue(8)
hey.enqueue(7)
hey.enqueue(0)
hey.enqueue(9)
print(len(hey))
print(hey.dequeue())
print(len(hey))
print(hey.dequeue())
print(hey.dequeue())
print(hey.dequeue())
print(len(hey))
hey.enqueue(8)
print(len(hey))
print(hey.dequeue())
print(hey.dequeue())
print(len(hey))
print(hey.dequeue()) | true |
f92006c08123e7458621351431b775866e431a3d | Alexis862/SWITCH_OKORO-CHIDERA | /count.py | 232 | 4.25 | 4 | # program to find out if a number is prime or not
num = eval(input('enter a number'))
flag = 0
for i in range(2,num):
if num%i==0:
flag = 1
if flag==1:
print('not prime')
else:
print('prime')
| true |
771692708f5a3242d3c0120acb30ba318afbc7df | andy-zhang201/file-organizers | /organize.py | 2,207 | 4.125 | 4 | import os
from pathlib import Path
"""
Runs a script that sorts files by their file types. Puts them into either a Documents, Audio, Videos,
Images, or a MISC folder.
"""
SUBDIRECTORIES = {
"DOCUMENTS": ['.pdf','.rtf','.txt'],
"AUDIO": ['.m4a','.m4b','.mp3'],
"VIDEOS": ['.mov','.avi','.mp4'],
"IMAGES": ['.jpg','.jpeg','.png']
}
"""
Returns a category based on the file suffix (eg: .pdf will return DOCUMENTS)
.mov will return VIDEOS
"""
def pickDirectory(value):
#Loop through all items in the dictionary.
#.items() returns a list of tuples containing all key-value pairs in the dict.
for category, suffixes in SUBDIRECTORIES.items():
#Loop through file suffixes, found in the second element of each tuple.
for suffix in suffixes:
#If a suffix matches the passed value, return the category of that suffix.
if suffix == value:
return category
#If no suffixes get matched, return MISC.
#This means that when no
return "MISC"
#Test:
#print(pickDirectory(".pdf"))
"""
Loop through every file in the working directory.
"""
def organizeDir():
#Loop through all items returned by .scandir(), which gives us the path names of all files.
for items in os.scandir():
#Skip if items is a directory.
if items.is_dir():
continue
#Find the directory path of each item using pathlib
filePath = Path(items)
#Find the file's suffix using .suffix()
fileSuffix = filePath.suffix.lower()
#Use pickDirectory funcion to determine directory name.
directory = pickDirectory(fileSuffix)
#Cast directory to path type.
directoryPath = Path(directory)
#If the directrroy path does not exist, make a new dir.
if directoryPath.is_dir() != True:
directoryPath.mkdir()
#Move the file to its respective directory.
#Done by renaming the filepath to include new folder.
#For more info: https://docs.python.org/3/library/pathlib.html
filePath.rename(directoryPath.joinpath(filePath))
#Call funciton to organize the dir.
organizeDir()
| true |
226979e89a4e1ff45948688c7e246a536ddc51f8 | wenqi0927/python-practice | /2017-12/2017-12-04.py | 1,598 | 4.1875 | 4 | """
list 列表
"""
list1 = ["Google","Runoob",1997,2000]
list1[0]=1
list1[1:]=["a","b","c"]
print(list1)
#赋值,返回值[1,"a","b","c"],赋值只能在索引范围内,上面的列表不能赋值list1[4]
del list1[0]
print(list1)
#删除元素,返回值['a','b','c']
#嵌套列表
a=['a','b','c']
b=[1,2,3]
x=[a,b]
#x返回值为[['a','b','c'],[1,2,3]]
print(len(x),x[0],x[0][1])
#返回值2,['a','b','c'],b
print("========================================")
#取最大/最小值
list2=[1,2,3,4,5]
print(max(list2))
print(min(list2))
#5,1
list3=[[1,2,3],[4,5,6]]
print(max(list3))
print(min(list3))
#[4,5,6] [1,2,3]
#list4=['a',1,2,3]
#print(max(list4))
#print(min(list4))
#无法读取,str和int
a=[1,2,3,4]
b=[4,5,7,7]
a.append(b)
print(a)
#返回值[1,2,3,4,[4,5,7,7]]
print(b.count(7))
#返回值2,返回7在b中出现的次数
a=[1,2,3,4]
b=[4,5,7,7]
a.extend(b)
print(a)
#返回值[1,2,3,4,4,5,7,7]
print(a.index(4))
#返回值3,返回4在a中第一次出现的索引值
m=[1,2,3]
m.insert(1,8)
print(m)
#返回值[1,8,2,3],insert[1,8]是将8插入索引是1的位置
print(m.pop())
#返回值3,pop()是删除列表最后一个元素并返回删除的值
n=[1,2,8,9,8]
n.remove(8)
print(n)
#返回值[1,2,9,8],remove() 函数用于移除列表中某个值的第一个匹配项
m.reverse()
print(m)
#返回值[2,8,1],reverse反向列表中元素
aList = ['xyz', 'zara', 'abc', 'xyz','mnopq']
aList.sort()
print(aList)
aList.sort(key=len)
print(aList)
#排序
a=[1,2,3,4,4]
print(a.clear())
#返回值None
a=[1,2,3,4,5]
print(a.copy())
b=a.copy()
print(b)
| false |
0afd799ce9b3d5f4b8c2ef0aa2ebb9ee5383080e | Ajax12345/My-Python-Projects | /Calculator_Function_Project.py | 933 | 4.1875 | 4 | def what_type():
while True:
ans = raw_input("Enter the type of operation you would like to use i.e add, subtract, multiply, or divide: ")
if ans == "add":
add()
elif ans == "subtract":
subtract()
elif ans == "multiply":
multiply()
elif ans == "divide":
divide()
answer = raw_input("Do you want to run again? ")
if answer == 'y' or answer == 'yes':
continue
else:
print "Thank you for trying our new calculator"
break
def add():
x = input()
y = input()
sum = x + y
print sum
def subtract():
x = input()
y = input()
remainder = x - y
print remainder
def multiply():
x = input()
y = input()
product = x*y
print product
def divide():
x = input()
y = input()
quotient = round(x/y, 5)
print quotient
what_type()
| true |
cb90e2702cebdbb487a0d044eb2d4f2b5c26e03b | ToporovV/algorithms | /lesson_3/les_3_task_3.py | 708 | 4.25 | 4 | # В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
import random
SIZE = 10
MIN_ITEM = 0
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
min_ = 0
max_ = 0
for i in range(len(array)):
if array[i] < array[min_]:
min_ = i
elif array[i] > array[max_]:
max_ = i
print(f'Минимальный элемент массива {array[min_]} ')
print(f'Максимальный элемент массива {array[max_]} ')
array[min_], array[max_] = array[max_], array[min_]
print(f'Измененный массив: {array}')
| false |
f30b4bc30e2ba1949ea3b8df6b0a63c014b2452c | SeanValley/DailyProblems | /2020-02/2-24-20/Solution.py | 881 | 4.125 | 4 | #main() contains tests for possibleDecrypts()
#possibleDecrypts(message) will return how many possible messages
#can be deciphered from a given string of numbers
#where 1=a, 2=b, 3=c, etc.
def main():
totalPossible = possibleDecrypts("111")
print(totalPossible)
totalPossible = possibleDecrypts("123")
print(totalPossible)
totalPossible = possibleDecrypts("35116433234167")
print(totalPossible)
def possibleDecrypts(message):
length = len(message)
if length == 1:
#Can only be 1
return 1
elif length == 2:
#Can either be 2 digit number or 2 1 digit numbers
if int(message) <= 26:
return 2
else:
return 1
totalPossible = possibleDecrypts(message[1:])
if int(message[0:2]) <= 26:
totalPossible += possibleDecrypts(message[2:])
return totalPossible
main()
| true |
ce50c81e64a841f3f2643b758b6d24ff4fc98a3b | SvetlanaSumets11/python-education | /structures/stack.py | 1,418 | 4.28125 | 4 | """This module to implement the stack"""
from linked_list import LinkedListNode
class Stack:
"""This stack class"""
def __init__(self):
self.head = None
def is_empty(self):
"""Checking if a list is empty"""
return self.head is None
def __len__(self):
current, ind = self.head, 0
while current is not None:
current = current.next
ind += 1
return ind
def push(self, value):
"""Method for adding a node to the list"""
node = LinkedListNode(value)
if self.is_empty():
self.head = node
else:
node.next = self.head
self.head = node
def pop(self):
"""Remove stack node"""
if self.is_empty():
print("Стек пуст")
else:
self.head = self.head.next
def peek(self):
"""Stack node view method"""
if self.is_empty():
print("Стек пуст")
else:
return self.head.value
def __str__(self):
curr = self.head
string = ''
while curr is not None:
string += str(curr.value)
string +=' -> '
curr = curr.next
string += 'None'
return string
# stack = Stack()
# stack.push(3)
# stack.push(12)
# print(stack.peek())
# print(len(stack))
# print(stack)
# stack.pop()
# print(stack)
| true |
a9393a5886a5e9196bc7399cf48c50f8d0ba6fa6 | Owaisaaa/Python_Basics | /loops.py | 1,035 | 4.1875 | 4 | ############## While Loop ###############
while True:
print('Whats your name : ')
name = input()
if name != 'owais':
continue
print("Hey! Owais. Tell me your password ")
password = input()
if password == 'lion':
break
print("Access Granted! Welcome to the hunt.")
############### for Loop ################
total = 0
for num in range(101):
total = total + num
print(" The sum of numbers from 0 to 100 is : " + str(total))
######### version 2 ##########
print("Second version of for loop")
for i in range(2, 8):
print(i)
######### version 3 ##########
print("3rd version of for loop")
for i in range(0, 10, 2):
print(i)
######### version 4 ##########
print("4th version of for loop")
for i in range(8, -2, -1): # 3rd argument in range() function allows to run a loop in reverse order with one step
print(i)
################### import packages ######################
import random
print('We can print random numbers between any two numbers say 1 and 10')
for i in range(6):
print(random.randint(1,10))
| true |
d668bedf8abbf20776ee0c922292b017d10e881d | Shasanka1/python_work | /storing_data_json.py | 1,066 | 4.125 | 4 | '''
The json module allows you to dump simple python data structures into a file and
load the data from a file the next time the program runs.
You can also use json to share data between different Python programs.
even better, the json data format is not specific to Python,
so you can share to any other programmer.
'''
# JSON ( Javascript Object Notation) format was before for Javascript, but most programs use it
# The first program is to store a set of numbers and another program that reads those numbers back to memory
# using json.dump() to store set numbers and json.load() to read.
# Example
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
# now using json load...
with open(filename) as f_obj:
numbers = json.load(f_obj)
# Saving and Reading user generated data
username = input("What is your name?");
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We will remember you when you comeback..")
| true |
0d7918304456dec076371ec0d1f4b53823444565 | MarcioRSanches/Estudos_Python | /Desafio037.py | 680 | 4.1875 | 4 | num = int(input('Digite um numero: '))
print('''Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL''')
opcao = int(input('Sua opção: '))
if opcao == 1:
print('{} convertido para BINÁRIO é igual a {} '.format(num, bin(num) [2:]))
# o [2:] é o fatiamento para não aparecer as duas primeiras letras que são iguais para cada tipo
elif opcao == 2:
print('{} convertido para OCTAL é igual a {} '.format(num, oct(num) [2:]))
elif opcao == 3:
print('{} convertido para HEXADECIMAL é igual a {} '.format(num, hex(num) [2:]))
else:
print('Opção inválida. Tente novamente.')
| false |
dad71b9a664b6338e5a66d72ded909e8140c0299 | TerryKash/Problem_exercsie | /Problem 4.py | 1,511 | 4.3125 | 4 | '''
A palindrome is a string which when reversed is equal to itself:
Examples of palindrome includes 616, mom, 676, 100001
You have to take a number as an input from the user. You have to find the next palindrome corresponding to that number.
Your first input should be ‘number of test cases’ and then take all the cases as input from the user
Input:
3
451
10
2133
Output:
Next palindrome for 451 is 454
Next palindrome for 10 is 11
Next palindrome for 2133 is 2222
'''
def reverse(num):
n = str(num)
r = n[::-1]
return r
n = int(input("How many numbers you want to check? "))
for i in range(n):
num= int(input("Enter any number :- "))
if str(num)==reverse(num):
print ("Already palindrome.")
else:
while True:
num+= 1
if str(num)==reverse(num):
print(f"Next palindrome is {num}")
break
# '''
# Author: Harry
# Date: 15 April 2019
# Purpose: Practice Problem For CodeWithHarry Channel
# '''
# def next_palindrome(n):
# n = n+1
# while not is_palindrome(n):
# n += 1
# return n
# def is_palindrome(n):
# return str(n) == str(n)[::-1]
# if __name__ == "__main__":
# n = int(input("Enter the number of test cases\n"))
# numbers = []
# for i in range(n):
# number = int(input(f"Enter the {i+1} number:\n"))
# numbers.append(number)
# for i in range(n):
# print(f"Next palindrome for {numbers[i]} is {next_palindrome(numbers[i])}")
| true |
1f3a67576eb6e841747d27467ab4d5a7ee5c29b9 | mkurde/the-coding-interview | /problems/longest-words/longest-words.py | 1,118 | 4.25 | 4 | from string import lower
def longest_word(words):
"""
Runtime: O(n)
"""
longest = [""]
for w in words.split(" "):
w = lower(w)
if len(w) == len(longest[0]):
if w not in longest:
longest.append(w)
if len(lower(w)) > len(longest[0]):
longest = [w]
return longest
print longest_word("You are just an old antidisestablishmentarian") # ["antidisestablishmentarian"]
print longest_word("I gave a present to my parents") # ["present", "parents"]
print longest_word("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo") #["buffalo"] or ["Buffalo"]
# Another approach
def longest_word(words):
words = sorted(words.split(),key=len)
longest = []
for i in words:
if len(i) == len(words[-1]):
longest.append(i.lower())
return sorted(list(set(longest)))
print(longest_word("You are just an old antidisestablishmentarian")) # ['antidisestablishmentarian']
print(longest_word("I gave a present to my parents")) # ['parents', 'present']
print(longest_word("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo")) # ['buffalo']
| false |
bf5bb6b47025c6764cc025134b87efcc107fdb50 | zcbiner/beat-algorithm | /sorting-algorithm/src/merge_sort.py | 1,298 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ISort import ISort
class MergeSort(ISort):
def sort(self, arr):
left = 0
right = len(arr) - 1
self.mergeSort(arr, left, right)
# 将数组从中间分为两部分,然后合并
def mergeSort(self, arr, left, right):
if left >= right:
return
mid = left + (right - left) // 2
self.mergeSort(arr, left, mid)
self.mergeSort(arr, mid + 1, right)
self.merge(arr, left, mid, right)
# 合并两个数组,合并时要注意排序
def merge(self, arr, left, mid, right):
mergeNum = []
start = left
end = mid + 1
while start <= mid and end <= right:
if arr[start] <= arr[end]:
mergeNum.append(arr[start])
start += 1
else:
mergeNum.append(arr[end])
end += 1
while start <= mid:
mergeNum.append(arr[start])
start += 1
while end <= right:
mergeNum.append(arr[end])
end += 1
# 将辅助数组的数据拷贝回原数组
start = left
while start <= right:
arr[start] = mergeNum[start - left]
start += 1 | false |
f53de6e6dda1a01af17effb70d41ad43fdcfcacc | Pranav016/DS-Algo-in-Python | /Stack/CheckRedundantBrackets.py | 1,176 | 4.125 | 4 | # For a given expression in the form of a string, find if there exist any redundant brackets or not. It is given that the expression contains only rounded brackets or parenthesis and the input expression will always be balanced.
# A pair of the bracket is said to be redundant when a sub-expression is surrounded by unnecessary or needless brackets.
# Expression: (a+b)+c
# Since there are no needless brackets, hence, the output must be 'false'.
# Expression: ((a+b))
# The expression can be reduced to (a+b). Hence the expression has redundant brackets and the output will be 'true'.
from sys import stdin
def checkRedundant(s):
if not s:
return False
stack=[]
c=0
i=0
while i<len(s):
if s[i]==')':
x=stack.pop()
while x!='(' and stack:
c+=1
x=stack.pop()
if c>1 and x=='(':
c=0
i+=1
continue
else:
return True
else:
stack.append(s[i])
i+=1
return False
#main
s = stdin.readline().strip()
if checkRedundant(s) :
print("true")
else :
print("false")
| true |
008a9e7f9d37db27d83bd5ac40d28f8a8bcc82c8 | Pranav016/DS-Algo-in-Python | /OOPS-1/Classes&Att.py | 1,265 | 4.34375 | 4 | # this is just for revision and reference purpose
# class attribute- present in every instance of the class
# instance attribute - present in that particular instance only
class Student:
name="Pranav" # class attribute
def student_details(self):
print(self.name)
def set_param(self): # this self parameter is used to recieve the instance(eg s1 or s2) during a func call
self.school="Institute of Technology"
s1=Student() # instance of the class
s1.age=20 # instance attribute
print(s1.__dict__) # helps to check/ print the instance attributes
s1.student_details()
s2=Student()
s2.batch=3 # instance attribute
s2.student_details() # class function to print the class attribute
print(s2.name) # can also print class or instance attribute directly using '.' operator
s3=Student()
s3.name="Rohan"
print(s3.batch) # this will give error since batch attr is instance attr of s2/ not a class attr
print(s3.name) # it first searches the instance attributes for 'name' and then checks the class attribute
# hence the instance attribute will be printed
#$ not so imp methods
print(hasattr(s3, "name")) # checks if the instance has that attr
print(getattr(s1, "age")) # gets the attr
delattr(s3, "name") #deletes the attr | true |
7e9acd2aa8c7a17164e942f5a284c1e5b5393dcf | frankzhuzi/ithm_py_hmwrk | /03_loop/hm_05_rowandcol.py | 230 | 4.15625 | 4 | row = 1
while row <= 5:
col = 1 # define col in the loop,so col will be reset everytime
while col <= row:
print("*", end="") # make no new row
col += 1
print("") # make a new row
row += 1
| true |
ce505843f694a0009e249241049c391d12c38370 | SonaliSihra/The-madlibs | /main.py | 1,932 | 4.25 | 4 | print("Lets begin the game of Madlibs!!")
print("The program will first prompt the user for a series of inputs a la Mad Libs. \n For example, a singular noun, "
"an adjective, etc. Then, once all the information has been inputted, \n the program will take that data and "
"place them into a pre-made story template.\n")
a = str(input("Today we are celebrating _holiday_"))
b = str(input("dinner at_relative_'s "))
c = str(input("house.When we arrived , my _relative_"))
d = str(input("Greeted us with a big _adjective_ kiss.")),
e = str(input("Kisses were so_adjective_"))
f = str(input("Now we're are just waiting for the_animal_"))
g = str(input("to come out of the oven. My dad is watching _sport_on TV."))
h = str(input("He always shout_exclamation_, "))
i = str(input("when his team scores a _noun_"))
j = str(input("Yesss _team name_--!!!"))
k = int(input("Only _minutes_"))
l = str(input("more minutes until the _animal_""will be ready!"))
m = str(input("I wonder if my mom will let me try the _animal_ "))
n = str(input("first.My grandma makes the best _flavour_"))
o = str(input("pie! It smells like a_noun_ "))
p = str(input("Happy _holiday_"))
print("TIME TO SEE THE RESULTS!!")
print("\nToday we are celebrating ", a, end='')
print(" dinner at ", b, "'s", end='')
print(" house.When we arrived , my ", c, end='')
print(" greeted us with a big ", d, end='')
print(" Kiss. Kisses were so ", e)
print("Now we're are just waiting for the ", f, end='')
print(" to come out of the oven. My dad is watching ", g, "on TV.", end='')
print("He always shout ", h, end='')
print(" when his team scores a ", i, end='')
print(" Yesss ", j, end='')
print(" \nOnly", k, end='')
print("more minutes until the ", l, "will be ready!!", end='')
print("I wonder if my mom will let me try the ", m, "first", end='')
print(" My grandma makes the best ", n, end='')
print(" pie! It smells like a ", o)
print(" Happy ", p, "!!")
| true |
1ff505554f77d728095c85111812a930c39cd49a | mathuesalexandre/cursoemvideo | /exe.33.py | 379 | 4.125 | 4 | a = int(input('Primeiro numero: '))
b = int(input('sugundo numero: '))
c = int(input('terceiro numero: '))
# Verificando o menor
menor = a
if b<a and b<c:
menor = b
if c<a and c<b:
menor = c
# verificando o maior
maior = a
if b>a and b>c:
maior = b
if c>a and c>b:
maior = c
print('o menor numero foi {}'.format(menor))
print('o maior numero foi {}'.format(maior))
| false |
b3fb2f6051b96f6245d0b6b4983108083145b1eb | KaindraDjoemena/Password-Manager | /Password-manager/cryptography.py | 2,277 | 4.21875 | 4 | import random
from random import choices
# The cryptography class
class Crypto:
# This sets the length of the random values and 5 chars is its default length
def __init__(self, length = 10):
self.length = length
# This method makes the key
def makeKey(self):
# The keys
value_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]|;:',<.>/?"
# The values
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]|;:',<.>/?"
key_dict = dict() # < Making an empty dict
# Assigns random chars from characters and concat them for them to be
# assign to on of the keys
for char in value_characters:
random_value = ""
if char == value_characters[0]:
for times in range(self.length):
random_char = random.choice(characters)
random_value += random_char
key_dict[char] = random_value
for key_char, value in key_dict.items():
random_value = ""
for times in range(self.length):
random_char = random.choice(characters)
random_value += random_char
# If the random value is equal to one of the values inside the dict,
# then generate another one
while random_value == value:
random_value = ""
for times in range(self.length):
random_char = random.choice(characters)
random_value += random_char
key_dict[char] = random_value # < Adds the key and the random value pair to the dict
return key_dict
# This method encrypts the message "x"
def encrypt(self, x, key):
encrypted_word = ""
char_list = list(x) # < Converting the string into a list
for char in char_list:
conv_char = key[char] # < For every index of the list/char, we turn it into the matching key's value
encrypted_word += conv_char
return encrypted_word
#this method decrypts the ecrypted message "x"
def decrypt(self, x, key):
decrypted_message = ""
seperated_enc_char = [x[i:i+self.length] for i in range(0, len(x), self.length)] # < Devides it by chunks
for enc_char in seperated_enc_char: # < Converts every chunk into chars
for letter, value in key.items():
if enc_char == value:
decrypted_message += letter
return decrypted_message | true |
24a3a0f417d5c08cab920f78bea4355d5577c36a | CxpKing/script_study | /python/class/classProperty.py | 2,425 | 4.46875 | 4 | '''class property
封装、抽象、继承、多态
'''
'''封装
封装包含两个概念:
1、将变量(状态)和方法(改变状态或执行涉及状态的计算)都集中在一个地方--对象本身
2、隐藏类的内部数据,以避免客户端(client)代码(即外部代码)直接访问对象变量
'''
class Demo(object):
def __init__(self):
self.num = [1,2,3,4,5]
print(self.num)
def change(self,index,data):
self.num[index] = data
d = Demo()
d.change(0,100)
print(d.num)
d.num[1] = 200
print(d.num)
'''抽象
将同一类事物将其共同的特征提取出来进行建模。
'''
'''继承
类似于java等编程语言的继承.创建类时,默认不写父类object时,python默认就是继承的object,所以我们自定义的父类,子类
父类就将object换为自己定义的类名即可,此时我们创建的类就是子类,其拥有了父类的public属性和方法。
% 当然继承也可以像java一样,可以有方法的重写
'''
class Father(object):
name = ""
age = 0
def __init__(self,name,age):
self.name = name
self.age = age
def fun(self):
print("Father's function!")
def __unsafe(self):
print("The fun is that children can't use ")
class Children(Father):
def fun(self):
print("Children changed father's fun!")
def skill(self,*skill):
self.skill = skill
father = Father("John",40)
children = Children("Bob",5)
print(children.name) #c.__num is error
print(children.age)
children.skill("打游戏","跑步")
print(children.skill)
class Dog(object):
def __init__(self,name,breed,owner):
self.name = name
self.breed = breed
self.owner = owner
def fun(self):
print("I'm a dog")
class Person(object):
def __init__(self,name):
self.name = name
jack = Person("jack")
dog = Dog("coco","TaiDi",jack)
print(dog.owner.name," has a dog named ",dog.name)
f = dog.fun
print(f)
f()
'''私有变量的处理
[description]
'''
class Cat(object):
__name = "jack"
def setName(self,name):
self.__name = name
def getName(self):
return self.__name
c = Cat()
print(c.getName())
c.setName("john")
print(c.getName())
class Student(object):
hobbies = []
def __init__(self,name):
self.name = name
def addHobby(self,hobby):
self.hobbies.append(hobby)
s = Student("cxp")
s.addHobby("读书")
s2 = Student("sss")
s2.addHobby("打游戏")
print(s.hobbies)
print(issubclass(Student,object))
| false |
7060c6829ec4a9e10171780b3dcfd7393e49949e | mohamed33reda33/courses | /programming/ITI/Python/intake_33/Presentations/Resources/Source Code/PythonProgs/answers/numbers.py | 362 | 4.15625 | 4 | #!/usr/bin/python
# This script reads in some
# numbers from the file 'numbers.txt'.
# It then prints out the smallest
# number, the arithmetic mean of
# the numbers, and the largest
# number.
import utils
data = open('numbers.txt')
numbers = []
for line in data:
numbers.append(float(line))
del line
data.close()
del data
print utils.stats(numbers)
| true |
4f38e3928035e32983260cb1b0b80a8d0a671e4f | MateuszJarosinski/PodstawyProgramowaniaDSW | /Semestr II/Labolatorium#16/2.py | 2,960 | 4.125 | 4 | import sqlite3
connection = sqlite3.connect('pracownicy')
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.executescript("""
DROP TABLE IF EXISTS pracownicy;
CREATE TABLE IF NOT EXISTS pracownicy (
id INTEGER PRIMARY KEY ASC,
imie VARCHAR(250) NOT NULL,
nazwisko VARCHAR(250) NOT NULL,
miejscowosc VARCHAR(250) NOT NULL,
zarobki INTEGER NOT NULL
)""")
cursor.execute('INSERT INTO pracownicy VALUES(NULL, "Mateusz", "Kapelusz", "Gdzieś na Podlasiu", 5000);')
cursor.execute('INSERT INTO pracownicy VALUES(NULL, "Bob", "Budowniczy", "Sosnowiec", 3000);')
cursor.execute('INSERT INTO pracownicy VALUES(NULL, "John", "Kowalsky", "UESEJ", 10000);')
def ShowEmployeesAlphabetically():
with connection:
cursor.execute('SELECT imie, nazwisko, miejscowosc, zarobki FROM pracownicy ORDER BY imie;')
employees = cursor.fetchall()
print("Lista pracowników posortowan alfabetycznie według imienia: ")
for employee in employees:
print(employee['imie'], employee['nazwisko'], employee['miejscowosc'], employee['zarobki'])
def AddEmployee():
with connection:
print("Dodaj pracownika: ")
name = input("Podaj imię: ")
surname = input("Podaj nazwisko: ")
town = input("Podaj miejscowość: ")
earnings = input("Podaj zarobki: ")
cursor.execute(f'INSERT INTO pracownicy VALUES (NULL,"{name}", "{surname}", "{town}", {earnings});')
print("Dodano pracownika")
def DismissEmployee():
with connection:
print("Zwolnij pracownika: ")
name = input("Podaj imię: ")
surname = input("Podaj nazwisko: ")
cursor.execute(f'DELETE FROM pracownicy WHERE imie = "{name}" AND nazwisko = "{surname}";')
print("Usunięto pracownika")
def SalaryInscrease():
with connection:
print("Zmień wynagrodzenie pracownika: ")
name = input("Podaj imię: ")
surname = input("Podaj nazwisko: ")
earnings = int(input("Podaj nowe wynagrodzenie: "))
cursor.execute(f'UPDATE pracownicy SET zarobki = {earnings} WHERE imie = "{name}" AND nazwisko = "{surname}";')
print("Zaktualizowano wynagrodzenie pracownika")
def ShowEarningsDescending():
with connection:
print("Lista zarobków pracowników od największych do najmiejszych: ")
cursor.execute('SELECT imie, nazwisko, miejscowosc, zarobki FROM pracownicy ORDER BY zarobki DESC;')
earnigs = cursor.fetchall()
for person in earnigs:
print(person['zarobki'], person['imie'], person['nazwisko'])
def ShowEarningsAnscending():
with connection:
print("Lista zarobków pracowników od najmiejszych do największych: ")
cursor.execute('SELECT imie, nazwisko, miejscowosc, zarobki FROM pracownicy ORDER BY zarobki ASC;')
earnigs = cursor.fetchall()
for person in earnigs:
print(person['zarobki'], person['imie'], person['nazwisko'])
| false |
4248c5bcf596a022d412c41c3589c6d929d3034d | hyattj-osu/advent_of_code_2020 | /day03/day03.py | 2,306 | 4.125 | 4 |
"""
From your starting position at the top-left, check the position that is right 3 and down 1. Then, check the position
that is right 3 and down 1 from there, and so on until you go past the bottom of the map.
The same pattern repeats to the right many times
Starting at the top-left corner of your map and following a slope of right 3 and down 1, how many trees would you
encounter?
"""
def part1(lines):
num_trees = 0
hor_index = 0
width = len(lines[0])
for index, line in enumerate(lines):
if index == 0: # skip counting the first line since we move down initially
continue
hor_index += 3
if hor_index >= width: # since the pattern repeats to the right, loop around
hor_index -= width
if line[hor_index] == '#':
num_trees += 1
print(f'Part 1: {num_trees}')
return()
def check_trees(layout, hshift, vshift):
num_trees = 0
width = len(layout[0])
height = len(layout)
hor_index = 0
ver_index = vshift
while 0 <= ver_index < height:
hor_index += hshift
if hor_index >= width:
hor_index -= width
elif hor_index < 0:
hor_index = width + hor_index
if layout[ver_index][hor_index] == '#':
num_trees += 1
ver_index += vshift
return(num_trees)
"""
Determine the number of trees you would encounter if, for each of the following slopes, you start at the top-left corner
and traverse the map all the way to the bottom:
Right 1, down 1.
Right 3, down 1. (This is the slope you already checked.)
Right 5, down 1.
Right 7, down 1.
Right 1, down 2.
"""
def part2(lines):
list_trees = []
list_trees.append(check_trees(lines, 1, 1))
list_trees.append(check_trees(lines, 3, 1))
list_trees.append(check_trees(lines, 5, 1))
list_trees.append(check_trees(lines, 7, 1))
list_trees.append(check_trees(lines, 1, 2))
answer = 1
for num_trees in list_trees:
answer *= num_trees
print(f'Part 2: {answer}')
return()
def main():
lines = []
with open("./day03/input.txt", 'r') as infile:
for line in infile:
lines.append(line.rstrip('\n'))
part1(lines)
part2(lines)
return()
if __name__ == "__main__":
main() | true |
2afb6ceb541d94975949f75b68119c2dc3dba4b4 | Abhilas-007/python-practice | /codes/lambda_map_reduce_filter.py | 516 | 4.125 | 4 | from functools import reduce
#def get_even(n):
#return n%2==0
nums=[2,4,2,5,7,8,4,6]
print("The numbers are",nums)
#evens=list(filter(get_even,nums))# by use of external written function
evens=list(filter(lambda a : a%2 ==0,nums))#By the help of lamda expression#
print("The even numbers are",evens)
doubles=list(map(lambda a:a*2,evens))#us eof map and lamda function#
print("The doubles of all even number s are",doubles)
sum=reduce(lambda a,b:a+b,doubles)
print("The sum of doubles of even numbers is",sum) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.