blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
8bf756db6183232e427214af5df6d0d67b19b98c
|
meraj-kashi/Acit4420
|
/lab-1/task-1.py
| 286
| 4.125
| 4
|
# This script ask user to enter a name and number of cookies
# script will print the name with cookies
name=input("Please enter your name: ")
number=int(input("Please enetr number of your cookies: "))
print(f'Hi {name}! welcome to my script. Here are your cookies:', number*'cookies ')
| true
|
9b80a85e7d931de6d78aeddeeccc2c154897a88b
|
vikrampruthvi5/pycharm-projects
|
/code_practice/04_json_experimenter_requestsLib.py
| 1,217
| 4.125
| 4
|
"""
Target of this program is to experiment with urllib.request library and understand GET and POST methods
Tasks:
1. Create json server locally
2. retrieve json file using url
3. process json data and perform some actions
4. Try POST method
"""
"""
1. Create json server locally
a. From terminal
install json-server : sudo npm install -g json-server
create a folder or file with json data ex: people.json
b. Start observing the json file
json-server --watch people.json
c. Make sure you are getting
Resources
http://localhost:3000/people
Home
http://localhost:3000
"""
"""
2. retrieve json file using url
"""
import urllib.request as req
import json
def get_json_data(url):
# Method to retrieve json data
data = req.urlopen(url)
data_json = json.loads(data.read())
return data_json
def post_json_data(url):
# Method posts json data to the json file under server
print("Post method")
def print_json_data(json):
for i in range(len(json)):
print(json[i]['name'],"is",json[i]['age'],"years old.")
json = get_json_data("http://localhost:3000/people")
print_json_data(json)
| true
|
5cb010b426cfff62548f9612eabbaad320954a78
|
vikrampruthvi5/pycharm-projects
|
/04_DS_ADS/02_dictionaries.py
| 1,038
| 4.4375
| 4
|
"""
Dictionaries : Just like the name says, KEY VALUE pairs exists
"""
friends = {
'samyuktha' : 'My wife',
'Badulla' : 'I hate him',
'Sampath' : 'Geek I like'
}
for k, v in friends.items(): # This can be used to iterate through the dictionary and print keys, values
print(k ,v)
"""
Trying dictionaries as values for a dictionary
Template:
'brand' : {
'model' : "",
'year' : YYYY,
'miles' : xxxxx.xx,
'owner' : ""
},
"""
cars = {
'Honda' : [
{
'model' : "Accord",
'year' : 2018,
'miles' : 30685.34,
'owner' : "Pruthvi"
},
{
'model' : "Accord",
'year' : 2018,
'miles' : 30685.34,
'owner' : "Pruthvi"
}
],
'Toyota' : [{
'model' : "Altis",
'year' : 2013,
'miles' : 3068.34,
'owner' : "Samyuktha"
}]
}
#Above : Each mode will have multiple cars
for k, v in cars.items():
print(k, v[0])
| false
|
aa322e4df062956a185267130057767ad450dc6e
|
JRose31/Binary-Lib
|
/binary.py
| 937
| 4.34375
| 4
|
''' converting a number into binary:
-Divide intial number by 2
-If no remainder results from previous operation, binary = 0,
else if remainder exists, round quotient down and binary = 1
-Repeat operation on remaining rounded-down quotient
-Operations complete when quotient(rounded down or not) == 0
'''
import math
def intToBinary(x):
convert = x
binary_holder = []
while convert > 0:
#dividing any number by 2 results in a remainder of 0 or 1
binary_holder.append(convert % 2)
#reassign rounded down quotient to our variable (convert)
convert = math.floor(convert//2)
#convert complete binary_holder list into string
holder_string = "".join([str(num) for num in binary_holder])
#our binary is backwards in the list (now a str) so we reverse it
binary_complete = holder_string[::-1]
return(binary_complete)
binary = intToBinary(13)
print(binary)
| true
|
5b17c79d9830601e3ca3f21b2d1aa8f334e93f13
|
piumallick/Python-Codes
|
/LeetCode/Problems/0104_maxDepthBinaryTree.py
| 1,405
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 20:12:03 2020
@author: piumallick
"""
# Problem 104: Maximum Depth of a Binary Tree
'''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the
longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
'''
class Node:
def __init__(self , val):
self.value = val
self.left = None
self.right = None
'''
def maxDepth(root):
if root == None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
'''
def maxDepth2(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
leftDepth = self.maxDepth2(root.left)
rightDepth = self.maxDepth2(root.right)
if leftDepth > rightDepth:
return leftDepth + 1
else:
return rightDepth + 1
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.right.right.left = Node(8)
root.right.left.right = Node(7)
print(root.maxDepth2(8))
| true
|
c5f5581f816bd354b3ee78d660c58aab13bb3906
|
piumallick/Python-Codes
|
/LeetCode/Leetcode 30 day Challenge/April 2020 - 30 Day LeetCode Challenge/02_isHappyNumber.py
| 1,406
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 22:49:19 2020
@author: piumallick
"""
# Day 2 Challenge
"""
Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Return True if n is a happy number, and False if not.
Example:
Input: 19
Output: true
"""
'''
let num = 123
let sum = 0
do while sum is not 1 {
do while num is greater than one digit number {
get number at index 1 of num
num = num // 10
calculate sum
}
calculate sum for the last digit in num
}
'''
def isHappyNumber(num):
sum = 0
numset = set()
while (sum != 1 and (num not in numset)):
numset.add(num)
sum = 0
while (num > 9):
rem = num % 10
rem_square = (rem ** 2)
sum += rem_square
num = num // 10
sum += (num ** 2)
num = sum
#print(numset)
return sum == 1
# Testing
if (isHappyNumber(2)):
print('Happy Number')
else:
print('Not a Happy Number')
| true
|
48a6871dba994b1244835a8fcc2a5edf9b206ca1
|
piumallick/Python-Codes
|
/LeetCode/Problems/0977_sortedSquares.py
| 909
| 4.1875
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 7 15:01:17 2020
@author: piumallick
"""
# Problem 977: Squares of a Sorted Array
'''
Given an array of integers A sorted in non-decreasing order,
return an array of the squares of each number,
also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
'''
def sortedSquares(A):
"""
:type A: List[int]
:rtype: List[int]
"""
res = []
for i in range(0, len(A)):
res.append(A[i] ** 2)
i += 1
return sorted(res)
def sortedSquares2(A):
return ([i*i for i in A])
# Testing
A = [1,2,3,4,5]
print(sortedSquares(A))
B = [-1, -2, 0, 7, 10]
print(sortedSquares2(B))
| true
|
3da3dfcf8bdba08539c1a0ecb23f7a908a8718f6
|
piumallick/Python-Codes
|
/LeetCode/Problems/0009_isPalindrome.py
| 973
| 4.25
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 15:46:03 2020
@author: piumallick
"""
# Problem 9: Palindrome Number
"""
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
"""
def isPalindrome(n):
r = 0
x = n
if (n < 0):
return False
while (n > 0):
a = n % 10
r = (r * 10) + a
n = n // 10
print('x=',x)
print('r=',r)
if (x == r):
return True
else:
return False
n = 121
print(isPalindrome(n))
| true
|
a4b659635bbc3dbafabce7f53ea2f2387281daa3
|
piumallick/Python-Codes
|
/Misc/largestNumber.py
| 613
| 4.5625
| 5
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 27 10:59:35 2019
@author: piumallick
"""
# Python Program to find out the largest number in the array
# Function to find out the maximum number in the array
def largestNumber(arr, n):
# Initialize the maximum element
max = arr[0]
#Traverse the array to find out the max element
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max
# Driver Code
arr = [10, 20, 30, 50, 40, 90, 5]
n = len(arr)
print('The largest number in the array is',largestNumber(arr,n),'.')
| true
|
78784eb5050732e41908bbb136a0bac6881bc29b
|
phenom11218/python_concordia_course
|
/Class 2/escape_characters.py
| 399
| 4.25
| 4
|
my_text = "this is a quote symbol"
my_text2 = 'this is a quote " symbol' #Bad Way
my_text3 = "this is a quote \" symbol"
my_text4 = "this is a \' \n quote \n symbol" #extra line
print(my_text)
print(my_text2)
print(my_text3)
print(my_text4)
print("*" * 10)
line_length = input("What length is the line?" >)
character = input("What character should I use?")
print(character*int(line_length))
| true
|
5ce0153e690d86edc4b835656d290cda02caa2c7
|
plee-lmco/python-algorithm-and-data-structure
|
/leetcode/23_Merge_k_Sorted_Lists.py
| 1,584
| 4.15625
| 4
|
# 23. Merge k Sorted Lists hard Hard
#
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
#
# Example:
#
# Input:
# [
# 1->4->5,
# 1->3->4,
# 2->6
# ]
# Output: 1->1->2->3->4->4->5->6
def __init__(self):
self.counter = itertools.count()
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
return self.use_priority_queue(lists)
def use_priority_queue(self, lists: List[ListNode]) -> ListNode:
'''
Runtime: 164 ms, faster than 26.43% of Python3 online submissions for Merge k Sorted Lists.
Memory Usage: 16.9 MB, less than 32.59% of Python3 online submissions for Merge k Sorted Lists.
'''
# Create priority queue
q = PriorityQueue()
# Create head of link list
head = ListNode(0)
curr_node = head
# Loop through all the list
# Put the first linked list in Priority Queue
for link in lists:
# ensure link list defined
if link:
# Add to queue
# In python 3 to avoid duplicate elements in tuple caused comparison
# failure like "TypeError: '<' not supported between instances of
# 'ListNode' and 'ListNode'", use a unique id as the second element
# in the tuple.
q.put((link.val, next(self.counter), link))
# While we go over all linked list
while (not q.empty()):
_, count, node = q.get()
curr_node.next = node
if node.next:
q.put((node.next.val, next(self.counter), node.next))
curr_node = node
return head.next
| true
|
cec13d4024f52f100c8075e5f1b43408790377bb
|
aquatiger/misc.-exercises
|
/random word game.py
| 1,175
| 4.5625
| 5
|
# does not do what I want it to do; not sure why
# user chooses random word from a tuple
# computer prints out all words in jumbled form
# user is told how many letters are in the chosen word
# user gets only 5 guesses
import random
# creates the tuple to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
word = random.choice(WORDS)
correct = word
jumble = ""
count = 0
score = 5
"""
Welcom to Random Word Game
From the list of scrambled words,
Choose the one the computer chose.
"""
print("The word is ", len(word), "letters long.")
# print(word)
for word in WORDS:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):] * (len(word))
print(jumble)
guess = input("\nYour guess is: ")
while guess != correct and guess != "":
print(guess)
if guess == correct:
print("That's it! You guessed correcntly!\n")
print("Thanks for playing!")
input("\nPress the enter key to exit.")
"""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
"""
| true
|
30be4f414ed675c15f39ccf62e33924c7eb9db3b
|
Deepanshudangi/MLH-INIT-2022
|
/Day 2/Sort list.py
| 348
| 4.46875
| 4
|
# Python Program to Sort List in Ascending Order
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
NumList.sort()
print("Element After Sorting List in Ascending Order is : ", NumList
| true
|
34028b34420e05f24493049df0c8b5b0391eb9b9
|
sammaurya/python_training
|
/Assignment6/Ques4.py
| 879
| 4.4375
| 4
|
'''
We have a function named calculate_sum(list) which is calculating the sum of the list.
Someone wants to modify the behaviour in a way such that:
1. It should calculate only sum of even numbers from the given list.
2. Obtained sum should always be odd. If the sum is even, make it odd by adding +1 and
if the sum is odd do nothing
Write two decorators that would serve these two purposes and use them in the above function.
'''
def even_sum(func):
def wrapper(list):
even_list = [value for value in list if value % 2 == 0]
return func(even_list)
return wrapper
def make_odd(func):
def wrapper(list):
sum = func(list)
if sum % 2 == 0:
return sum + 1
return sum
return wrapper
@make_odd
@even_sum
def calculate_sum(list):
return sum(list)
list = [1,2,3,4,5,6,7,8,9,10]
print(calculate_sum(list))
| true
|
2b5069c18e127d08dbaf55b1e0c7da11f1f87440
|
sammaurya/python_training
|
/classes.py
| 1,090
| 4.1875
| 4
|
# class A:
# def __init__(self):
# self.name = "sam"
# self._num = 9 #protected
# self.__age = 22 #private
# a = A()
# print(a.name, a._num)
# a.__age = 23
# print(a._A__age)
# print(dir(a))
# a = 8
# b=10
# print(a.__add__(2))
# for i in range(5):
# print(i)
# print(range(5))
# class Parent:
# def __init__(self,name='Parent',age='52'):
# self.name = name
# self.age = age
# def __str__(self):
# return "{0.name} is {0.age} years old.".format(self)
# class Child(Parent):
# def __init__(self, name='child',parent='Parent',age='52'):
# super().__init__(parent,age)
# self.name = name
# def do(self):
# print("Doing...")
# def __str__(self):
# return "Hey Child"
# c = Child('sam','rahul','22')
# c.do()
# p = Parent('Rakesh','45')
# print(p)
# # p.do()
# print(c)
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
print(MyClass.i, MyClass.f(MyClass))
print(MyClass().f())
print(type(MyClass.f))
| false
|
44f4b11f6819b285c3698ab59571f03591ad72b8
|
sahilsehgal81/python3
|
/computesquareroot.py
| 308
| 4.125
| 4
|
#!/usr/bin/python
value = eval(input('Enter the number to find square root: '))
root = 1.0;
diff = root*root - value
while diff > 0.00000001 or diff < -0.00000001:
root = (root + value/root) / 2
print(root, 'squared is', root*root)
diff = root*root - value
print('Square root of', value, "=", root)
| true
|
cfcd0baa03e8b3534f59607103dfec97f760ea28
|
zoeang/pythoncourse2018
|
/day03/exercise03.py
| 699
| 4.40625
| 4
|
## Write a function that counts how many vowels are in a word
## Raise a TypeError with an informative message if 'word' is passed as an integer
## When done, run the test file in the terminal and see your results.
def count_vowels(word):
if (type(word)==str)==False:
raise TypeError, "Enter a string."
else:
vowels= ['a','e','i','o','u'] #list of vowels
word_letters=[i for i in word] #store each letter of the word as an element of a list
number_of_vowels=0
for i in word_letters: #for each letter in the word
if i in vowels: #check if the letter is in the list of vowels
#print i + ' is a vowel.'
number_of_vowels+=1
return number_of_vowels
# to run, navigate to file
| true
|
bb7941ec61dab5e4798f20fb78222c933efdcfe4
|
Quantum-Anomaly/codecademy
|
/intensive-python3/unit3w4d6project.py
| 757
| 4.5
| 4
|
#!/usr/bin/env python3
toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms']
prices = [2,6,1,3,2,7,2]
num_pizzas = len(toppings)
#figure out how many pizzas you sell
print("we sell " + str(num_pizzas) + " different kinds of pizza!")
#combine into one list with the prices attached to the slice
pizzas = list(zip(prices,toppings))
print(pizzas)
#here is the sorting magic
sorted_pizzas = sorted(pizzas)
print(sorted_pizzas)
#cheapest pizza
cheapest_pizza = sorted_pizzas[0]
#most expensive pizza
priciest_pizza = sorted_pizzas[-1]
#three of the cheapest
three_cheapest = sorted_pizzas [:3]
print(three_cheapest)
#how many 2 dollar items are there?
num_two_dollar_slices = prices.count(2)
print(num_two_dollar_slices)
| true
|
8ad608b134e6244dc51b15a8b94e33fd316a063d
|
Huynh-Soup/huynh_story
|
/second.py
| 391
| 4.1875
| 4
|
"""
Write a program that will ask the user what thier age is and then
determine if they are old enough to vote or not and respond appropriatlely
"""
age = int(input("Hello, how old are you?: "))
if age < 17 :
print("You can't vote")
if age > 18 :
print("Great, who would you vote for in 2020? (a,b,c) ")
print("a. Kanye West (Yeezy) ")
print("b.Donald Trump")
print("c.")
| false
|
544c379a54a69a59d25a1241727d02f9414d6d1b
|
Murrkeys/pattern-search
|
/calculate_similarity.py
| 1,633
| 4.25
| 4
|
"""
Purpose : Define a function that calculates the similarity between one
data segment and a given pattern.
Created on 15/4/2020
@author: Murray Keogh
Program description:
Write a function that calculates the similarity between a data segment
and a given pattern. If the segment is shorter than the pattern,
print out 'Error' message.
Data dictionary:
calculate_similarity : Function that calculate similarity
ds : Numpy array of given data segment
patt : Numpy array of given pattern
output : Output of function, float or string
data_segment : given segment of data
pattern : given pattern list
"""
import numpy as np
def calculate_similarity(data_segment, pattern):
""" Calculate the similarity between one data segment and the pattern.
Parameters
----------
data_segment : [float]
A list of float values to compare against the pattern.
pattern : [float]
A list of float values representing the pattern.
Returns
-------
float
The similarity score/value.
"Error"
If data segment and pattern are not the same length.
"""
# Assign given float lists to numpy array variables
ds = np.array(data_segment)
patt = np.array(pattern)
#Check if length of segment is shorter than length of pattern
if len(ds) != len(patt):
output = 'Error' #Assign 'Error' to output
else:
output = np.sum(ds*patt) #assign similarity calculation to output
return output
| true
|
13593ebd81e6210edd3981895623975c820a72bc
|
MurrayLisa/pands-problem-set
|
/Solution-2.py
| 367
| 4.4375
| 4
|
# Solution-2 - Lisa Murray
#Import Library
import datetime
#Assigning todays date and time from datetime to variable day
day = datetime.datetime.today().weekday()
# Tuesday is day 1 and thursday is day 3 in the weekday method in the datetime library
if day == 1 or day == 3:
print ("Yes - today begins with a T")
else:
print ("No Today does not begin with a T")
| true
|
00c63f2572974a410eb7dfeaad043c1e067dfdf4
|
room29/python
|
/FOR.py
| 1,820
| 4.21875
| 4
|
# lista en python
mi_lista = ['pocho', 'sander', 'caca']
for nombre in mi_lista:
print (nombre)
# Realizar un programa que imprima en pantalla los números del 20 al 30.
for x in range(20,31):
print(x)
'''La función range puede tener dos parámetros, el primero indica el valor inicial que tomará la variable x,
cada vuelta del for la variable x toma el valor siguiente hasta llegar al valor indicado por el segundo parámetro
de la función range menos uno.'''
#ESTRUCTURAS DE DATOS CON FOR
lista=[] # declaramos la lista
for k in range(10):
lista.append(input("introduce valor en lista:")) # añadimos los valores de la lista por teclado
print("los elementos de la lista son:"+str(lista)) # visualizamos los elementos de la lista
valor=int(input("introduce el valor a modificar de la lista pon el indice:")) # índice a modificar
nuevo=input ("introduce el nuevo valor:") # valor nuevo de índice que se modifica
lista[valor]=nuevo # hacemos la modificación
print("los elementos de la lista son:"+str(lista)) # visualizamos los elemntos para comprobar la modificación
valor=int(input("introduce el índice en el que se insertará el nuevo valor:")) # índice donde se inserta en nuevo valor
nuevo=input ("introduce el nuevo valor:") # valor a insertar
lista.insert(valor, nuevo)
print("los elementos de la lista son:"+str(lista)) # visualizamos los elemntos para comprobar la modificación
nuevo=input ("introduce el valor a eliminar:") # valor a eliminar
lista.remove(nuevo) # eliminamos el valor
print("los elementos de la lista son:"+str(lista)) # visulaizamos lista
nuevo=input ("introduce el valor a buscar:")
resultado=(nuevo in lista)
if (resultado):
print ("existe este elemento y su índice es:"+str(lista.index(nuevo)))
else:
print("no exite es elemento")
| false
|
c0babd8461d2df8c5c3fe535b4fcc9ae15464adf
|
dcassells/Project-Euler
|
/project_euler001.py
| 565
| 4.46875
| 4
|
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def three_multiple(x):
if x%3 == 0:
return 1
else:
return 0
def five_multiple(x):
if x%5 == 0:
return 1
else:
return 0
def three_five_multiple_sum(a):
multi_sum = 0
for i in range(a):
if three_multiple(i):
multi_sum = multi_sum + i
elif five_multiple(i):
multi_sum = multi_sum + i
return multi_sum
print(three_five_multiple_sum(1000))
| true
|
5af9348c7a72d67d0985911be231eb92519c8610
|
elagina/Codility
|
/lessons/lesson_1.py
| 580
| 4.15625
| 4
|
"""
Codility
Lesson 1 - Iterations
BinaryGap - Find longest sequence of zeros in binary representation of an integer.
"""
def solution(N):
bin_N = str("{0:b}".format(N))
max_counter = 0
counter = 0
for ch in bin_N:
if ch == '1':
if max_counter < counter:
max_counter = counter
counter = 0
else:
counter += 1
return max_counter
def main():
N = 9
print 'Binary Gap Problem'
print 'Input:\n', 'N =', N
print 'Output:\n ', solution(N)
if __name__ == '__main__':
main()
| true
|
b3bd54dd4116a00744311a671f01040d70799f98
|
josemigueldev/algoritmos
|
/07_factorial.py
| 442
| 4.21875
| 4
|
# Factorial de un número
def factorial(num):
result = 1
if num < 0:
return "Sorry, factorial does not exist for negative numbers"
elif num == 0:
return "The factorial of 0 is 1"
else:
for i in range(1, num + 1):
result = result * i
return f"The factorial of {num} is {result}"
if __name__ == "__main__":
number = int(input("Enter a number: "))
print(factorial(number))
| true
|
c5cdfbda5e8cb293bb7773ef345ddb5c8157313e
|
udhay1415/Python
|
/oop.py
| 861
| 4.46875
| 4
|
# Example 1
class Dog():
# Class object attribute
species = "mammal"
def __init__(self, breed):
self.breed = breed
# Instantation
myDog = Dog('pug');
print(myDog.species);
# Example 2
class Circle():
pi = 2.14
def __init__(self, radius):
self.radius = radius
# Object method
def calculateArea(self):
return self.radius*self.radius*self.pi
myCircle = Circle(2);
print(myCircle.radius);
print(myCircle.calculateArea());
# Example - Inheritance
class Animal(): # Base class
def __init__(self):
print('Animal created')
def eating(self):
print('Animal eating')
class Lion(Animal): # Derived class that can access the methods and properties of base class
def __init__(self):
print('Lion created')
myLion = Lion()
myLion.eating()
| true
|
f7ba7fbb5be395558e1d8451e6904279db95952d
|
Nour833/MultiCalculator
|
/equation.py
| 2,637
| 4.125
| 4
|
from termcolor import colored
import string
def equation():
print(colored("----------------------------------------------------------------", "magenta"))
print(colored("1 ", "green"), colored(".", "red"), colored("1 dgree", "yellow"))
print(colored("2 ", "green"), colored(".", "red"), colored("2 degree", "yellow"))
print(colored("98", "green"), colored(".", "red"), colored("return to home menu", "yellow"))
print(colored("99", "green"), colored(".", "red"), colored("exit", "yellow"))
try :
aq = int(input(colored("""Enter your selected number here
==>""", "blue")))
except :
print(colored("please select the right number", "red"))
equation()
try :
if aq == 1:
print(colored("Exemple : ax+b ", "red"))
b = int(input(colored("Enter b : ", "green")))
a = int(input(colored("Enter a : ", "green")))
x = -b/a
if type(x) == float:
print(colored("x = " + str(x), "magenta"),colored("or (another form) x = " + str(-b) + "/ "+str(a), "magenta"))
else:
print(colored("x = "+str(x),"magenta"))
elif aq == 2:
a = int(input(colored("Enter a : ","green")))
b = int(input(colored("Enter b : ", "green")))
c = int(input(colored("Enter c : ","green")))
Delta = b ** 2 - 4 * a * c
rdelta = Delta**(1/2)
if type(rdelta)==float:
rDelta= "√"+str(Delta)
else:
rDelta = rdelta
if Delta == 0:
x = -b / (2 * a)
if type(x)==float:
print(colored("x = "+str(x),"cyan")," or ",colored("x = "+str(-b)+"/ "+str(2*a),"cyan"))
elif Delta < 0:
print("X hasn't solution")
else:
x1 = (-b + rdelta) / (2 * a)
x2 = (-b - rdelta) / (2 * a)
if type(x1) == float:
x1 = str(x1)+" or/or "+"( "+str(-b)+"+"+str(rDelta)+" ) "+"/ "+str(a*2)
else:
x1 = x1
if type(x2) == float:
x2 = str(x2)+" or/or "+"( "+str(-b)+"-"+str(rDelta)+" ) "+"/ "+str(a*2)
else:
x2=x2
print(colored("x1 = "+x1,"cyan"),"and",colored("x2 = "+x2,"cyan"))
elif aq == 98:
eq=1
return eq
elif aq == 99:
exit()
except:
print(colored("please select the right number", "red"))
equation()
| true
|
f9d07c3b4fbdc162b266613270fb975eac8e097d
|
lidongdongbuaa/leetcode2.0
|
/位运算/汉明距离/461. Hamming Distance.py
| 1,551
| 4.28125
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/1/16 20:33
# @Author : LI Dongdong
# @FileName: 461. Hamming Distance.py
''''''
'''
题目分析
1.要求:The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Input: x = 1, y = 4 Output: 2 Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different
2.理解:求两个数的相同位置上不同数的发生次数和
3.类型:bit manipulation
4.边界条件:0 ≤ x, y < 2**31.
4.方法及方法分析:bit compare, XOR + count 1
time complexity order: O(1)
space complexity order: O(1)
'''
'''
A.
思路:brute force - bit compare
方法:
1. compare bit one by one
if dif, add numb
time complex: O(32) = O(1)
space complex: O(1)
易错点:
'''
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
numb = 0
for i in range(32):
if (x >> i & 1) != (y >> i & 1):
numb += 1
return numb
x = Solution()
print(x.hammingDistance(1, 4))
'''
B.
优点:不用32位遍历
思路:XOR + count 1 (可用191的各种方法替换)
方法:
1. transfer dif value to 1
2. count 1
time complex: O(i) = O(1), i is numb of 1
space complex: O(1)
易错点:
'''
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
z = x ^ y
numb = 0
while z != 0:
z = z & z - 1
numb += 1
return numb
| true
|
e88f7472da1d78f89cd3a23e98c97c3bc054fba7
|
lidongdongbuaa/leetcode2.0
|
/二叉树/二叉树的遍历/DFS/145. Binary Tree Postorder Traversal.py
| 1,978
| 4.15625
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/2/19 20:15
# @Author : LI Dongdong
# @FileName: 145. Binary Tree Postorder Traversal.py
''''''
'''
题目分析
1.要求:
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output:
Follow up: Recursive solution is trivial, could you do it iteratively?
2.理解: post order the tree, output the node val in list
3.类型: binary tree
4.确认输入输出及边界条件:
input: tree root with API, repeated? Y order? N value range? N
output: list[int]
corner case:
None -> []
only one -> [int]
4.方法及方法分析:
time complexity order:
space complexity order:
'''
'''
dfs from top to down
'''
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root: # corner case
return []
res = []
def dfs(root): # scan every node
if not root: # base case
return
dfs(root.left)
dfs(root.right)
res.append(root.val)
return root
dfs(root)
return res
'''
dfs bottom up
'''
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
l = self.postorderTraversal(root.left)
r = self.postorderTraversal(root.right)
return l + r + [root.val]
'''
dfs iteration
'''
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
if not root: # corner case
return []
stack = [root]
res = []
while stack:
root = stack.pop()
res.append(root.val)
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
return res[::-1]
| true
|
7b2ffd07955b5c356405909fc2649e6f88a5542d
|
lidongdongbuaa/leetcode2.0
|
/位运算/数学相关问题/201. Bitwise AND of Numbers Range.py
| 1,796
| 4.15625
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/1/18 9:39
# @Author : LI Dongdong
# @FileName: 201. Bitwise AND of Numbers Range.py
''''''
'''
题目分析
1.要求:Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1: Input: [5,7] Output: 4
Example 2:Input: [0,1]Output: 0
2.理解:二进制数字针对每一位数,相对应的与
3.类型:bit
4.确认输入输出及边界条件:
input: list, int, inclusive, 0<= m <= n <= 2**31 - 1
4.方法及方法分析:& one by one, calculate same number in left of binary number
time complexity order: calculate same number in left of binary number O(1) < & one by one O(1)
space complexity order: calculate same number in left of binary number O(1) = & one by one O(1)
'''
'''
思路:brute force
方法:& one by one
time complex: O(n - m + 1)
space complex: O(1)
易错点:res = m 不能为 res = 1,因为1是00001,前面的数bitwise后就归零了
'''
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
if m == n: # corner case
return m
res = m
for elem in range(m + 1, n + 1):
res = (res & elem)
return res
x = Solution()
print(x.rangeBitwiseAnd(0, 1))
'''
思路:calculate same number in left of binary number
方法:
1. build mask of 31* 1
2. find the left common, output
time complex: O(1)
space complex: O(1)
易错点:
'''
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
if m == n: # corner case
return m
mask = (1 << 31) - 1
while (m & mask) != (n & mask):
mask = mask << 1
return n & mask
x = Solution()
print(x.rangeBitwiseAnd(26, 30))
| false
|
8a4ccf34efe6041af0f3d69dae882df49b30d0e8
|
lidongdongbuaa/leetcode2.0
|
/二分搜索/有明确的target/33. Search in Rotated Sorted Array.py
| 2,283
| 4.21875
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/12 15:24
# @Author : LI Dongdong
# @FileName: 33. Search in Rotated Sorted 数组.py
''''''
'''
题目分析 - 本题重点看
find the target value in the sorted rotated array, return its index, else return -1
O(logN)
binary search problem
input: nums:list[int], repeated value in it? N; ordered, Y; len(nums) range? [1, 10000]; value range? [-2*32, 2*32]
output:int or -1
corner case:
nums is None? Y -> -1
nums is only one? Y -> as request
target is None? Y -> -1
5.方法及方法分析:brute force; binary search
time complexity order: binary search O(logN) < brute force O(N)
space complexity order: O(1)
6.如何考
'''
'''
A.brute force - traversal all value
Method:
traversal all elements in nums, and check the target, if having, return True, else return False
time complexity: O(N)
space complexity: O(1)
'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
for index, value in enumerate(nums):
if target == value:
return index
return -1
'''
A. Binary search
Method:
1. corner case
2. set left and right boundary
3. do while loop
a. set mid
b. if arr[mid] == target, return mid
c. if l part is sorted, move boundary
d. if r part is sorted, move boudnary
Time complexity: O(logN)
Space: O(1)
'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: # corner case
return -1
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if target == nums[mid]:
return mid
if nums[l] < nums[mid]: # 判断左边有序
if nums[l] <= target < nums[mid]: # 因为此时target != nums[mid]
r = mid - 1
else:
l = mid + 1
elif nums[l] == nums[mid]: # 左边与mid相等
l = mid + 1
elif nums[l] > nums[mid]: # 右边有序
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return -1
| true
|
01aeba94e37e74be60c0b9232b80b18edcdf251e
|
lidongdongbuaa/leetcode2.0
|
/二叉树/路径和/257. Binary Tree Paths.py
| 2,842
| 4.1875
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/2/26 16:16
# @Author : LI Dongdong
# @FileName: 257. Binary Tree Paths.py
''''''
'''
题目分析
1.要求:Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
2.理解:scan all tree node and return string with ->
3.类型:binary tree path
4.确认输入输出及边界条件:
input: tree root node with definition, the node's value range? N, number of node? N, repeated? Y ordered? N
output: list[string]
corner case:
None:[]
5.方法及方法分析:DFS, BFS
time complexity order: O(N)
space complexity order: O(N)
6.如何考: 没法考oa
'''
'''
dfs from top to bottom
time complexity: O(n)
space:O(n) skewed tree
dfs(root, path)
'''
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: # corner case
return []
self.res = []
def dfs(root, path): # scan every node and save leaf path to res
if not root: # base case
return
if not root.left and not root.right:
self.res.append(path[:])
if root.left:
dfs(root.left, path + '->' + str(root.left.val))
if root.right:
dfs(root.right, path + '->' + str(root.right.val))
return
dfs(root, str(root.val))
return self.res
'''
dfs iteration
right - left
'''
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: # corner case
return []
res = []
stack = [[root, str(root.val)]]
while stack:
root, path = stack.pop()
if not root.left and not root.right:
res.append(path[:])
if root.right:
stack.append([root.right, path + '->' + str(root.right.val)])
if root.left:
stack.append([root.left, path + '->' + str(root.left.val)])
return res
'''
bfs
'''
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: # corner case
return []
res = []
from collections import deque
queue = deque([[root, str(root.val)]])
while queue:
root, path = queue.popleft()
if not root.left and not root.right:
res.append(path[:])
if root.left:
queue.append([root.left, path + '->' + str(root.left.val)])
if root.right:
queue.append([root.right, path + '->' + str(root.right.val)])
return res
| true
|
7fab504e2bf2fbdf95ba142fb630b38fb34b4ab4
|
lidongdongbuaa/leetcode2.0
|
/二分搜索/有明确的target/367. Valid Perfect Square.py
| 2,926
| 4.34375
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/12 11:19
# @Author : LI Dongdong
# @FileName: 367. Valid Perfect Square.py
''''''
'''
题目分析
1.要求:Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
2.理解: find a number which could square as the given num
3.类型: search problem
4.确认输入输出及边界条件:
input: int, num range? [1, 100000]
output: T/F
corner case:
num <= 0? N
num would be 1? Y -> T
num is None? N
5.方法及方法分析:Brute force; binary search; Newton Method
time complexity order: binary search O(logN) = Newton Method O(logN) < Brute force O(N)
space complexity order: O(1)
6.如何考
'''
'''
A. Brute force
Method:
1. traversal number from 1 to half of num to check if the number * number is num
if true, return true
else return False
time complexity: O(n)
space : O(1)
易错点:
'''
class Num:
def isSqare(self, num): # return True of square num, else return Faslse
if num == 1: # corner case
return 1
for i in range(1, num // 2):
if i * i == num:
return True
return False
'''
B. binary search the result from 1 to half of num
Method:
1. set left boundary, l, as 1, set right boundary,r, as num//2
2. do while traversal, l <= r
a. mid = (l + r)//2
b. check if the mid^2 == num?
return True
c. mid^2 < num
l = mid + 1
d. mid^2 > num
r = mid - 1
time O(logN)
space O(1)
'''
class Num:
def isSquare(self, num: int): # return True if num is perfect square, False for no prefect square
if num == 1:
return True
l = 1
r = num // 2
while l <= r:
mid = (l + r) // 2
tmp = mid * mid
if tmp == num:
return True
elif tmp < num:
l = mid + 1
elif tmp > num:
r = mid - 1
return False
'''
test code
input: 16
l:1, r:8
loop1:
mid = 4
tmp = 16
tmp == num -> return True
input: 14 = num
l:1, r: 7
loop1:
mid = 4
tmp = 16
tmp > num
r = 3
loop2:
mid = 2
tmp = 4 < num
l = 2 + 1 = 3
loop3
mid = 3
tmp = 9 < num
l = mid + 1 = 4
out of loop
return False
'''
'''
C.Newton
time O(logN)
space O(1)
'''
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if num == 1:
return True
x = num // 2
while x * x > num:
x = (x + num // x) // 2
return x * x == num
| true
|
656d6352c80b070e9760832e961a7c3443ed5c94
|
lidongdongbuaa/leetcode2.0
|
/二分搜索/有明确的target/81. Search in Rotated Sorted Array II.py
| 2,724
| 4.1875
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/17 11:18
# @Author : LI Dongdong
# @FileName: 81. Search in Rotated Sorted 数组 II.py
''''''
'''
题目概述:在rotated sorted array里面找目标值
题目考点: 在分块后,块可能不是sorted的,出现头值l和尾值mid重复,怎么处理
解决方案: 不断缩进left part的left边界,直到l不等于mid,此时left块是sorted,再进行binary search
方法及方法分析:brute force, binary search
time complexity order: binary search, worst O(N) = brute force O(N)
space complexity order: O(1)
如何考
'''
'''
find value in a repeated value sorted rotated array
input:
nums, list; length rang of list? [0,+1000]; value range? [-10000, 1000]; repeated? Y
target, int: None? Y; out of range of nums? Y
output:
True, find the target
False
A. brute force - scan one by one
Time complexity: O(N)
Space: O(1)
B. binary search, first set then do
Method:
1. corner case
2. transfer list as set to remove repeated values, then transfer as list
3. find the target in list by binary search
a. divide by mid
b. find the target, in sorted part and in unsorted parted
Time: O(N)
space: O(N)
corner case: Nums is None, target is None
C. Method:
1. corner case
2. set left and right boundary;
3. do while loop and use mid to divide the nums into left and right part
if find, return True
if left part's head = tail, traversal left boundary to make the left part sorted
if left part is sorted, check target in left or right part, then scale the boundary
if right part is sorted, do the same thing
Time complexity: worst O(N) [1,1,1,1...]
Space: O(1)
易错点:
1. 一定要对着method写代码,不要漏
2. r - l顺序不要弄反了
3. nums[mid] = target不要漏
4. if elif else是并列关系,不要ififelse!
'''
class Solution:
def search(self, nums: List[int], target: int) -> bool:
if nums is None: # corner case
return False
if target is None:
return False
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if nums[mid] == target:
return True
if nums[l] == nums[mid]:
l += 1
elif nums[l] < nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return False
| false
|
b20e9404095fe9b959a709747ef4685a3ac5798a
|
lidongdongbuaa/leetcode2.0
|
/二分搜索/没有明确的target/458. Last Position of Target (Lintcode).py
| 1,173
| 4.21875
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/12 18:52
# @Author : LI Dongdong
# @FileName: 458. Last Position of Target (Lintcode).py
''''''
'''
题目分析
Description
Find the last position of a target number in a sorted array. Return -1 if target does not exist.
Example Given [1, 2, 2, 4, 5, 5].
For target = 2, return 2.
For target = 5, return 5.
For target = 6, return -1.
理解:想象是在找一个比target大的且不存在的数的前值,即模板1的r值
方法及方法分析:
time complexity order:
space complexity order:
6.如何考
'''
'''
'''
class Solution:
def lastPosition(self, nums, target):
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if nums[mid] == target: # 因为要找末尾值,故继续往mid的右边寻找
l = mid + 1
if target < nums[mid]:
r = mid - 1
elif nums[mid] < target:
l = mid + 1
if r < 0:
return -1
else:
if nums[r] == target:
return r
else:
return -1
| false
|
c7c49fdd8806c4b5e06b0502cb892511d82cec67
|
lidongdongbuaa/leetcode2.0
|
/数据结构与算法基础/leetcode周赛/200301/How Many Numbers Are Smaller Than the Current Number.py
| 1,974
| 4.125
| 4
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/1 11:32
# @Author : LI Dongdong
# @FileName: How Many Numbers Are Smaller Than the Current Number.py
''''''
'''
题目分析
1.要求:
2.理解:in a arr, count how many elem in this list < list[i], output
3.类型:array
4.确认输入输出及边界条件:
input: list, length? 2<= <= 500; value range? 0<= <= 100, repeated? Y, order? N
output: list[int]
corner case: None? N, only One? N
5.方法及方法分析:
time complexity order:
space complexity order:
6.如何考
'''
'''
A. Brute force
Method:
1. scan elem in list one by one
scan other elem in list
count the numb of smaller
save count in res
2. return res
time complexity O(N**2), space O(N)
易错点:
'''
class Solution:
def smallerNumbersThanCurrent(self, nums): # return list[int]
res = []
for i in range(len(nums)):
tmp = 0
for j in range(0, i):
if nums[j] < nums[i]:
tmp += 1
for k in range(i + 1, len(nums)):
if nums[k] < nums[i]:
tmp += 1
res.append(tmp)
return res
'''
test case
nums = [6,5,4,8]
loop 1:
i = 0
tmp = 0
j in (0,0)
j in (1, 4)
tmp + 1 + 1 = 2
res [2]
loop 2:
i = 1
tmp = 0
j in(0,1)
j in (2,4) tmp + 1
res [2, 1]
loop 3
i = 2
tmp = 0
j in (0:2) tmp 0
j in (3,4) tmp 0
res [2,1,0]
loop 4
i = 3
tmp = 0
j in (0,3) tmp + 3
j in (4, 4) tmp + 0
res [2,1,0,3]
'''
'''
B. optimized code
'''
class Solution:
def smallerNumbersThanCurrent(self, nums): # return list[int]
res = []
for i in range(len(nums)):
tmp = 0
for j in range(len(nums)):
if j != i and nums[j] < nums[i]:
tmp += 1
res.append(tmp)
return res
| true
|
51a7a056f3efed50e627e4e07e0b63053e4f499e
|
masskro0/test_generator_drivebuild
|
/utils/plotter.py
| 1,910
| 4.5625
| 5
|
"""This file offers several plotting methods to visualize functions or roads."""
import matplotlib.pyplot as plt
import numpy as np
def plotter(control_points):
"""Plots every point and lines between them. Used to visualize a road.
:param control_points: List of points as dict type.
:return: Void.
"""
point_list = []
for point in control_points:
point_list.append((point.get("x"), point.get("y")))
point_list = np.asarray(point_list)
x = point_list[:, 0]
y = point_list[:, 1]
plt.plot(x, y, '-og', markersize=10, linewidth=control_points[0].get("width"))
plt.xlim([min(x) - 0.3, max(x) + 0.3])
plt.ylim([min(y) - 0.3, max(y) + 0.3])
plt.title('Road overview')
plt.show()
def plot_all(population):
"""Plots a whole population. Method starts a new figure for every individual.
:param population: Population with individuals in dict form containing another dict type called control_points.
:return: Void
"""
iterator = 0
while iterator < len(population):
plotter(population[iterator].get("control_points"))
iterator += 1
def plot_lines(lines):
"""Plots LineStrings of the package shapely. Can be also used to plot other geometries.
:param lines: List of lines, e.g. LineStrings
:return: Void
"""
iterator = 0
while iterator < len(lines):
x, y = lines[iterator].xy
plt.plot(x, y, '-og', markersize=3)
iterator += 1
# plt.show()
def plot_splines_and_width(width_lines, control_point_lines):
"""Plots connected control points with their width lines.
:param width_lines: List of lines (e.g. LineStrings) which represent the width of a road segment.
:param control_point_lines: List of connected control points (e.g. LineStrings).
:return: Void.
"""
plot_lines(width_lines)
plot_lines(control_point_lines)
plt.show()
| true
|
0e6b1edba6cc8b19d81a97ba4af49a79f41bca5c
|
TomasHalko/pythonSchool
|
/School exercises/day_2_exercise_5.py
| 789
| 4.28125
| 4
|
dictionary = {'cat': 'macka', 'dog': 'pes', 'hamster': 'skrecok', 'your_mom': 'tvoja mama'}
print("Welcome to the English to Slovak translator.")
print("---------------------------------------------")
print("English\t - \tSlovak")
print("---------------------------------------------")
for key,value in dictionary.items():
print(str(key) + "\t is \t" + str(value))
word = input(str('Which word to translate?'))
for key,value in dictionary.items():
if word in dictionary:
translation = dictionary[word]
print('The translation for', word, 'is', translation)
exit()
if word not in dictionary:
print("Sorry I cannot translate the word.")
exit()
#how to invert the dictionary --> inverted = {v: k for k,v in dictionary.items()}
| false
|
7265ea38cd157f595842c3ef9b309107ce72703a
|
FalseFelix/pythoncalc
|
/Mood.py
| 381
| 4.1875
| 4
|
operation=input("what mood are you in? ")
if operation=="happy":
print("It is great to see you happy!")
elif operation=="nervous":
print("Take a deep breath 3 times.")
elif operation=="sad":
print("kill yourself")
elif operation == "excited":
print("cool down")
elif operation == "relaxed":
print("drink red bull")
else:
print("I don't recognize this mood")
| true
|
fc080b5de22363064f268a18b5fd5767d3fc170f
|
wcleonard/PythonBridge
|
/Algorithm/sort/heap_sort.py
| 2,472
| 4.375
| 4
|
# @Time : 2019/4/21 0:49
# @Author : Noah
# @File : heap_sort.py
# @Software: PyCharm
# @description: python -m doctest -v heap_sort.py
# 利用堆这种数据结构所设计的一种排序算法
# 堆是一个近似完全二叉树的结构
# 并同时满足堆积的性质:
# 每个结点的值都大于或等于其左右孩子结点的值,称为大顶堆
# 每个结点的值都小于或等于其左右孩子结点的值,称为小顶堆
# heapify函数作用是将待排序序列构造成一个大顶堆,此时整个序列的最大值就是堆顶的根节点
def heapify(unsorted, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
heapify(unsorted, largest, heap_size)
def heap_sort(unsorted):
'''
Pure implementation of the heap sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
# >>> heap_sort([0, 5, 3, 2, 2])
# [0, 2, 2, 3, 5]
# >>> heap_sort([])
# []
# >>> heap_sort([-2, -5, -45])
[-45, -5, -2]
'''
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
# 将堆顶元素与末尾元素进行交换,使末尾元素最大
# 然后继续调整堆,再将堆顶元素与末尾元素交换得到第二大元素
# 如此反复进行交换、重建、交换
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted
if __name__ == "__main__":
lst = [23, 17, 29, 10, 15, 12, 24, 19]
sorted_lst = heap_sort(lst)
print(sorted_lst)
# 再简单总结下堆排序的基本思路:
#
# a.将无需序列构建成一个堆,根据升序降序需求选择大顶堆或小顶堆;
#
# b.将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端;
#
# c.重新调整结构使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整+交换步骤,直到整个序列有序
| false
|
20b4b1e4590ec30986cd951656926c9777e9b35b
|
kingdayx/pythonTreehouse
|
/hello.py
| 1,232
| 4.21875
| 4
|
SERVICE_CHARGE = 2
TICKET_PRICE =10
tickets_remaining = 100
# create calculate_price function. It takes tickets and returns TICKET_PRICE * tickets
def calculate_price(number_of_tickets):
# add the service charge to our result
return TICKET_PRICE * number_of_tickets + SERVICE_CHARGE
while tickets_remaining:
print("There are {} tickets remaining".format(tickets_remaining))
name = input("What is your name? ")
tickets = input("Hey {} , How many tickets would you like? ".format(name))
try:
tickets = int(tickets)
if tickets > tickets_remaining:
raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
print("oh no! we ran into an issue. {} please try again".format(err))
else:
total_cost = calculate_price(tickets)
print("Your tickets cost only {}".format(total_cost))
proceed = input("Do you want to proceed? /n (Enter yes/no)")
if proceed == "yes":
# To do: gather credit card info and process it
print("SOLD!!")
tickets_remaining -= tickets
else:
print("Thank you, {}!!".format(name))
print("Tickets are sold out!!")
| true
|
6bb6ae0cb5373c6619deda59adfbf5a33263419e
|
darshikasingh/tathastu_week_of_code
|
/day 3/program3.py
| 271
| 4.34375
| 4
|
def duplicate(string):
duplicateString = ""
for x in string:
if x not in duplicateString:
duplicateString += x
return duplicateString
string = input("ENTER THE STRING")
print("STRING AFTER REMOVING DUPLICATION IS", duplicate(string))
| true
|
bb62403136e8af65bfecf341f083bb6c1db0b2de
|
annalyha/iba
|
/For_unit.py
| 949
| 4.28125
| 4
|
#Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами a и b на квадраты
# с наибольшей возможной на каждом этапе стороной.
# Выведите длины ребер получаемых квадратов и кол-во полученных квадратов.
a = int(input("Длина стороны a: "))
b = int(input("Ширина стороны b: "))
n = 0
def recursia(a, b, n):
if a == 0 or b == 0:
print("Количество полученных квадратов - ", n)
return
if a > b:
print("Длина ребра квадрата - ", b)
recursia(a - b, b, n + 1)
else:
print("Длина ребра квадрата - ", a)
recursia(a, b - a, n + 1)
recursia(a, b, n)
| false
|
b15f207ad94ebec1fd8365a66a54563c1589e958
|
vrashi/python-coding-practice
|
/upsidedowndigit.py
| 228
| 4.25
| 4
|
# to print the usside-down triangle of digits
row = int(input("Enter number of rows"))
a = row
for i in range(row+1, 0, -1):
for j in range(i+1, 2, -1):
print(a, end = " ")
a = a - 1
print()
a = row
| true
|
394e5870361f046e78b91c28e4a0b9584e2cb158
|
os-utep-master/python-intro-Jroman5
|
/wordCount.py
| 1,513
| 4.125
| 4
|
import sys
import string
import re
import os
textInput =""
textOutput =""
def fileFinder():
global textInput
global textOutput
if len(sys.argv) is not 3:
print("Correct usage: wordCount.py <input text file> <output file>")
exit()
textInput = sys.argv[1]
textOutput = sys.argv[2]
if not os.path.exists(textInput):
print("text file input %s doesn't exist! Exiting" %textInput)
exit()
#Reads file, removes punctuation and returns a list of words in alphabetical order, and in lowercase
def fileReader(file):
try:
text = open(file,"r")
words = text.read()
pattern = "[\"\'!?;:,.-]"
#table = words.maketrans("!;',.?:\"-"," ")
#words = words.translate(table)
words = re.sub(pattern," ",words)
seperatedWords = words.split()
seperatedWords = [element.lower() for element in seperatedWords]
seperatedWords.sort()
finally:
text.close()
return seperatedWords
#Takes a list of words and places them in a dictionary with the word as a key and the occurrences as its value
def wordCounter(words):
wordCount = {}
for x in words:
if(x in wordCount):
wordCount[x] = wordCount[x] + 1
else:
wordCount[x] = 1
return wordCount
#Writes the counted words to a file
def fileWriter(countedWords):
try:
file = open(textOutput,"w+")
for x in countedWords:
file.write(x + " " + str(countedWords[x]) + "\n")
finally:
file.close()
#main method
if __name__=="__main__":
fileFinder()
organizedWords=fileReader(textInput)
fileWriter(wordCounter(organizedWords))
| true
|
0008d5d1d0598ec37b494351fe76f7d0fd49011b
|
AdityanBaskaran/AdityanInterviewSolutions
|
/Python scripts/evenumbers.py
| 371
| 4.125
| 4
|
listlength = int(input('Enter the length of the list ... '))
numlist = []
for x in range(listlength):
number = int(input('Please enter a number: '))
numlist.append(number)
numlist.sort()
def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print (is_even_num(numlist))
print (is_even_num(numlist))
| true
|
e9741e14864c9005a628a75da45532e32d4c3697
|
Jocapear/TC1014
|
/WSQ05.py
| 224
| 4.125
| 4
|
f = float(input("Give me your temperature in F°"))
c = float(5 * (f - 32)/9)
print(f,"F° is equivalent to ",c,"C°.")
if(c>99):
print("Water will boil at ",c,"C°.")
else:
print("Water will NOT boil at ",c,"C°.")
| false
|
4914e373050abc2fc202a357d4e8a82ee7bd87c7
|
laurakressin/PythonProjects
|
/TheHardWay/ex20.py
| 920
| 4.1875
| 4
|
from sys import argv
script, input_file = argv
# reads off the lines in a file
def print_all(f):
print f.read()
# sets reference point to the beginning of the file
def rewind(f):
f.seek(0)
# prints the line number before reading out each line in the file
def print_a_line(line_count, f):
print line_count, f.readline(),
# sets var current_file to the second input in the argv
current_file = open(input_file)
# activating the defs
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
# setting variable current_line(1)
current_line = 1
print_a_line(current_line, current_file)
# incrementing variable current_line(2)
current_line += 1
print_a_line(current_line, current_file)
# again incrementing variable current_line(3)
current_line += 1
print_a_line(current_line, current_file)
| true
|
c9f68086ab8f97bad4b3b1c1961a0216f655f14c
|
cscoder99/CS.Martin
|
/codenow9.py
| 275
| 4.125
| 4
|
import random
lang = ['Konichiwa', 'Hola', 'Bonjour']
user1 = raw_input("Say hello in English so the computer can say it back in a foreign langauge: ")
if (user1 == 'Hello') or (user1 == 'hello'):
print random.choice(lang)
else:
print "That is not hello in English"
| true
|
6bac138771347788474a115b37b56b241d8cc8f7
|
anjosanap/faculdade
|
/1_semestre/logica_programacao/exercicios_apostila/estruturas_sequenciais_operadores_expressoes/ex6.py
| 298
| 4.15625
| 4
|
"""
Faça um programa que peça a temperatura em grausFahrenheit,
transforme e mostre a temperatura em graus Celsius.
"""
fahrenheit = float(input('Insira sua temperatura em graus Fahrenheit: '))
celsius = (fahrenheit - 32) * 5 / 9
print('Sua temperatura em Celsius é:', '%.1f' % celsius, 'ºC')
| false
|
2052521302b0654c70fc5e7065f4a2cd6ff71fb1
|
martinfoakes/word-counter-python
|
/wordcount/count__words.py
| 1,035
| 4.21875
| 4
|
#!/usr/bin/python
file = open('word_test.txt', 'r')
data = file.read()
file.close()
words = data.split(" ")
# Split the file contents by spaces, to get every word in it, then print
print('The words in this file are: ' + str(words))
num_words = len(words)
# Use the len() function to return the length of a list (words) to get the word count, then print
print('The number of words in this file is: ' + str(num_words))
lines = data.split('\n')
# Split the file contents by \n to get each individual line, then print
print('The separate lines in this file are: ' + str(lines))
# use the len() function again to get the number of lines there are
print('The number of lines, including empty lines, is: ' + str(len(lines)))
# To remove the empty lines from the array list, use a for loop
# the NOT keyword automatically checks for emptiness, if the current entry is empty then it gets
# removed from the array 'lines'
for l in lines:
if not l:
lines.remove(l)
print('The number of non-empty lines only is: ' + str(len(lines)))
| true
|
fbc2c2b14924d71905b9ad9097f2e9d7c9e541fc
|
davidobrien1/Programming-and-Scripting-Exercises
|
/collatz.py
| 1,533
| 4.78125
| 5
|
# David O'Brien, 2018-02-09
# Collatz: https://en.wikipedia.org/wiki/Collatz_conjecture
# Exercise Description: In the video lectures we discussed the Collatz conjecture.
# Complete the exercise discussed in the Collatz conjecture video by writing a
# single Python script that starts with an integer and repeatedly applies the
# Collatz function (divide by 2 if even, multiply by three and add 1 if odd) using a
# while loop and if statement. At each iteration, the current value of the integer
# should be printed to the screen. You can specify in your code the starting
# value of 17. If you wish to enhance your program, have the program ask the
# user for the integer instead of specifying a value at the start of your code.
# Add the script to your GitHub repository, as per the instruction in the
# Assessments section.
n = int(input("Please enter an integer: ")) # this line defines "n" and asks the user to input an integer. The int function converts the input to an integer
while n > 1: # the while statement keeps looping through the code while n > 1
if(n % 2 == 0): # this if statement states that if the remainder of n divided by 2 is equal to 0 i.e an even number
n = n/2 # n now becomes (n divided by 2) and
print(n) # print the value of n
elif(n % 2 == 1): # the elif statement says that, or else if the remainder of n divided by 2 is equal to 1 i.e an odd number
n = n * 3 + 1 # n now becomes (n multiplied by 3 plus 1) and
print(n) # print the value of n
| true
|
d31bfb61f8e01688b186e6ccf860c12f8b1184de
|
j-kincaid/LC101-practice-files
|
/LC101Practice/Ch13_Practice/Ch13_fractions.py
| 543
| 4.21875
| 4
|
class Fraction:
""" An example of a class for creating fractions """
def __init__(self, top, bottom): # defining numerator and denominator
self.num = top
self.den = bottom
def __repr__(self):
return str(self.num) + "/" + str(self.den)
def get_numerator(self):
return self.num
def get_denominator(self):
return self.den
def main():
rug = Fraction(5, 7)
print(rug)
print(rug.get_numerator())
print(rug.get_denominator())
if __name__ == "__main__":
main()
| true
|
878934e0c30544f1b8c659ed41f789f20d9ac809
|
j-kincaid/LC101-practice-files
|
/LC101Practice/Ch10_Practice/Ch10Assign.py
| 1,008
| 4.15625
| 4
|
def get_country_codes(prices):
# your code here
""" Return a string of country codes from a string of prices """
#_________________# 1. Break the string into a list.
prices = prices.split('$') # breaks the list into a list of elements.
#_________________# 2. Manipulate the individual elements.
#_________________# A. Remove integers
# nation = prices[0], prices[1]
length = len(prices)
for nation in (prices):
nation == prices[0:]
print(nation)
#_________________# B.
nations = []
for each_char in (0, prices, 2):
if each_char in prices[0:2]:
nation = each_char
nations = list(nations)
# lastitem = nations.pop()
print(nations)
#_________________# 3. Make it back into a string.
# set = []
# my_list = ["happy"]
# my_str = my_list[0][3:]
# my_str == 'py' # True ## Jonathan's example from slack
# print(" ".join(prices))
# don't include these tests in Vocareum
| true
|
01c29535868a34895b949fa842ba41393251e622
|
j-kincaid/LC101-practice-files
|
/LC101Practice/Ch9_Practice/Ch_9_Str_Methods.py
| 880
| 4.28125
| 4
|
#___________________STRING METHODS
# Strings are objects and they have their own methods.
# Some methods are ord and chr.
# Two more:
ss = "Hello, Kitty"
print(ss + " Original string")
ss = ss.upper()
print(ss + " .upper")
tt = ss.lower()
print(tt + " .lower")
cap = ss.capitalize() # Capitalizes the first character only.
print(cap + " .capitalize")
strp = ss.strip() # Returns a string with the
print(strp + " .strip") ## leading and trailing whitespace removed.
lstrp = ss.lstrip()
print(lstrp + " .lstrip") # Returns a string with the leading
# whitespace removed.
rstrp = ss.rstrip()
print(rstrp + " .rstrip") # Returns a string with the trailing
# whitespace removed.
cout = ss.count("T") # Returns number of occurrences of a character
print(cout)
news = ss.replace("T", "^") # replaces all occurrences of an old substring
print(news) # with a new one.
| true
|
c2570e4c6ef6f4d83565952d783fa681eed14981
|
lunaxtasy/school_work
|
/primes/prime.py
| 670
| 4.34375
| 4
|
"""
Assignment 3 - Prime Factors
prime.py -- Write the application code here
"""
def generate_prime_factors(unprime):
"""
This function will generate the prime factors of a provided integer
Hopefully
"""
if isinstance(unprime, int) is False:
raise ValueError
factors = []
#for calls of 1, which is not prime
while unprime < 2:
break
#for calls of 2, which is prime
else:
for prime_fac in range(2, unprime + 1):
while (unprime % prime_fac) == 0: #checking that the remainder is 0
factors.append(prime_fac)
unprime = unprime // prime_fac
return factors
| true
|
b241bbd11590407332240b8254c911742e4382cc
|
TangMartin/CS50x-Introduction-to-Computer-Science
|
/PythonPractice/oddoreven.py
| 264
| 4.28125
| 4
|
number = -1
while(number <= 0):
number = int(input("Number: "))
if(number % 2 == 0 and number % 4 != 0):
print("Number is Even")
elif(number % 2 == 0 and number % 4 == 0):
print("Number is a multiple of four")
else:
print("Number is Odd")
| true
|
32d0aa6e3c5c083e6db1e174c3726a3ae99835ab
|
Kartavya-verma/Competitive-Pratice
|
/PyLearn/demo1.py
| 362
| 4.125
| 4
|
'''for i in range(0,5,1):
for j in range(0,5,1):
if j<=i:
print("*",end="")
print()'''
'''for i in range(6):
for j in range(6-i):
print("*",end="")
print()'''
q=int(input("Enter a num: "))
for i in range(2,q):
if q%i==0:
print("Not a prime num")
break
else:
print("Prime num")
| false
|
36020e1b3eaa7ce3cfd732813f6f86b0948245e3
|
Kartavya-verma/Competitive-Pratice
|
/Linked List/insert_new_node_between_2_nodes.py
| 1,888
| 4.125
| 4
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def inserthead(self, newnode):
tempnode = self.head
self.head = newnode
self.head.next = tempnode
del tempnode
def listlength(self):
currentnode = self.head
len = 0
while currentnode is not None:
len += 1
currentnode = currentnode.next
return len
def insertat(self, newnode, pos):
if pos < 10 or pos > self.listlength():
print("Invalid Position")
return
if pos is 0:
self.inserthead(newnode)
return
currentnode = self.head
currentpos = 0
while True:
if currentpos == pos:
previousnode.next = newnode
newnode.next = currentnode
break
previousnode = currentnode
currentnode = currentnode.next
currentpos += 1
def insertend(self, newnode):
if self.head is None:
self.head = newnode
else:
lastnode = self.head
while True:
if lastnode.next is None:
break
lastnode = lastnode.next
lastnode.next = newnode
def printlist(self):
if self.head is None:
print("List is empty")
return
currentnode = self.head
while True:
if currentnode is None:
break
print(currentnode.data)
currentnode = currentnode.next
firstNode = Node(10)
linkedlist = LinkedList()
linkedlist.insertend(firstNode)
secondnode = Node(20)
linkedlist.insertend(secondnode)
thirdnode = Node(15)
linkedlist.insertat(thirdnode, 10)
linkedlist.printlist()
| true
|
34e7f7e3d1b5c3688c8091c12c360da3f4563c45
|
PoojaKushwah1402/Python_Basics
|
/Sets/join.py
| 1,642
| 4.8125
| 5
|
# join Two Sets
# There are several ways to join two or more sets in Python.
# You can use the union() method that returns a new set containing all items from both sets,
# or the update() method that inserts all the items from one set into another:
# The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c",1,2}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
# The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
#The intersection_update() method will keep only the items that are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple1"}
x.intersection_update(y)
print(x)
# The intersection() method will return a new set, that only contains the items that are present in both sets.
# Return a set that contains the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry",'apple'}
y = {"google", "microsoft", "apple",'apple'}
z = x.intersection(y)
print(z)
# The symmetric_difference_update() method will keep only the elements that are NOT present in both sets.
# Keep the items that are not present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
# The symmetric_difference() method will return a new set, that contains only the elements that are NOT
# present in both sets.
# Return a set that contains all items from both sets, except items that are present in both:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
| true
|
52355dd175d820141ce23ace508c0c73501a74b0
|
PoojaKushwah1402/Python_Basics
|
/variable.py
| 809
| 4.34375
| 4
|
price =10;#this value in the memory is going to convert into binary and then save it
price = 30
print(price,'price');
name = input('whats your name ?')
print('thats your name '+ name)
x, y, z = "Orange", "Banana", "Cherry" # Make sure the number of variables matches the number of values, or else you will get an error.
print(x,'x')
print(y,'y')
print(z,'z')
#python needs to externally typecast the values it doesnt typecast internally
# int()#converts to integer
# str()# converts to string
# type()# gives the current data type of variable
# Python has no command for declaring a variable.
# A variable is created the moment you first assign a value to it.
#Python is case sensitive
#Multi Words Variable Names
#Camel Case - myVariableName
#Pascal Case - MyVariableName
#snake Case - my_variable_name
| true
|
692f1ef93f6b188a9a3244d45c73239e18ded92c
|
PoojaKushwah1402/Python_Basics
|
/Sets/sets.py
| 999
| 4.15625
| 4
|
# Set is one of 4 built-in data types in Python used to store collections of data.
# A set is a collection which is both unordered and unindexed.
# Sets are written with curly brackets.
# Set items are unordered, unchangeable, and do not allow duplicate values.
# Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
# Sets cannot have two items with the same value.
#**Once a set is created, you cannot change its items, but you can add new items.
thisset = {"apple", "banana", "cherry"}
thisnewset = set(("apple", "banana", "cherry",'banana')) # note the double round-brackets
print(thisset,thisnewset)
# You cannot access items in a set by referring to an index or a key.
# But you can loop through the set items using a for loop, or ask if a specified value is
# present in a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
#if set is not changable then how can we add items to it?
| true
|
9df5a51bffcc602bc34b04de97ef2b65e1a7759f
|
PoojaKushwah1402/Python_Basics
|
/List/list.py
| 1,906
| 4.4375
| 4
|
#Unpack a Collection
# If you have a collection of values in a list, tuple etc. Python allows you extract the
#values into variables. This is called unpacking.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x,'x')
print(y,'y')
print(z,'z')
# Lists are one of 4 built-in data types in Python used to store collections of data, the other
# 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
#To determine how many items a list has, use the len() function:
#Negative indexing means start from the end
#-1 refers to the last item, -2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(len(thislist))
print(type(thislist)) #<class 'list'>
print(thislist[2:5])
#To determine if a specified item is present in a list use the in keyword:
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
print('here')
thislist[1:5] = ['hell','no']
print(thislist)
thislist.insert(2, "watermelon")
print(thislist)#['apple', 'hell', 'watermelon', 'no', 'melon', 'mango']
#To add an item to the end of the list, use the append() method:
# To insert a list item at a specified index, use the insert() method.
# The insert() method inserts an item at the specified index:
#To append elements from another list to the current list, use the extend() method.
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
#The remove() method removes the specified item.
thislist.remove("banana")
#The pop() method removes the specified index.
#If you do not specify the index, the pop() method removes the last item.
thislist.pop(1)
#The del keyword also removes the specified index:
del thislist[0]
#The del keyword can also delete the list completely.
del thislist
#The clear() method empties the list.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
| true
|
f87ea76282626fba9e5f4e590bfdf282304346d4
|
Franco414/DASO_C14
|
/Ejercicios_Extras/Unidad7/Ejercicio_7_4.py
| 1,649
| 4.46875
| 4
|
"""
a) Escribir una función que reciba dos vectores y devuelva su producto escalar.
b) Escribir una función que reciba dos vectores y devuelva si son o no ortogonales.
c) Escribir una función que reciba dos vectores y devuelva si son paralelos o no.
d) Escribir una función que reciba un vector y devuelva su norma.
"""
def obt_producto_escalar(vector_a,vector_b):
if(len(vector_a)!=len(vector_b)):
ret=-1
else:
ret=0
for i in range(0,len(vector_a)):
ret=ret+vector_b[i]*vector_a[i]
return ret
a=(3,2,5)
b=(1,6,4)
res=obt_producto_escalar(a,b)
print("el producto escalar es ==>",res)
#b)
def son_ortogonales(vector_a,vector_b):
res=obt_producto_escalar(vector_a,vector_b)
if(res==0):
ret=True
else:
ret=False
return ret
a=(0,2,3)
b=(18,3,4)
res=son_ortogonales(a,b)
if(res):
print("Los vectores son ortogonales")
else:
print("Los vectores no son ortogonales")
#d)
def obt_norma_vector(vector):
from math import sqrt
norma=0
aux=0
for i in range(0,len(vector)):
aux=aux+vector[i]*vector[i]
norma=sqrt(aux)
return norma
c=(4,2,5)
res=obt_norma_vector(c)
print("La norma del vector es ==>",res)
#c)
def son_paralelos(vector_a,vector_b):
aux=obt_producto_escalar(vector_a,vector_b)
norma_A=obt_norma_vector(vector_a)
norma_B=obt_norma_vector(vector_b)
aux2=norma_A*norma_B
if(aux==aux2 or aux==(aux2*-1)):
ret=True
else:
ret=False
return ret
va=(2,4,6)
vb=(-1,-2,-3)
if(son_paralelos(va,vb)):
print("Los vectores son paralelos")
else:
print("Los vectores no son paralelos")
| false
|
dcfa6ed57445ecd90fdec3e3f5c431f0628bf3db
|
Franco414/DASO_C14
|
/Ejercicios_Extras/Unidad5/Ejercicio_5_9.py
| 816
| 4.375
| 4
|
"""
Ejercicio 5.9. Escribir una función que reciba dos números como parámetros, y devuelva cuántos múl-
tiplos del primero hay, que sean menores que el segundo.
a) Implementarla utilizando un ciclo for, desde el primer número hasta el segundo.
b) Implementarla utilizando un ciclo while, que multiplique el primer número hasta que sea ma-
yor que el segundo.
c) Comparar ambas implementaciones: ¿Cuál es más clara? ¿Cuál realiza menos operaciones?
"""
a=int(input("Ingrese un numero ==>"))
b=int(input("Ingrese un numero ==>"))
#a)
for i in range(a,b):
if(i%a==0):
if(i<b and i>a):
print("El siguiente numero es multiplo de a y menor que b ==>",i)
#b)
print("Apartado b")
c=a
j=2
while((a*j)<b):
print("El siguiente numero es multiplo de a y menor que b ==>",a*j)
j=j+1
| false
|
1749fc700b55dc9860bfe2f98b8336ee151c29ce
|
Franco414/DASO_C14
|
/Ejercicios_Extras/Unidad4/Ejercicio_4_4.py
| 1,727
| 4.28125
| 4
|
"""
Ejercicio 4.4. Escribir funciones que permitan encontrar:
a) El máximo o mínimo de un polinomio de segundo grado (dados los coeficientes a, b y c),
indicando si es un máximo o un mínimo.
b) Las raíces (reales o complejas) de un polinomio de segundo grado.
Nota: validar que las operaciones puedan efectuarse antes de realizarlas (no dividir por cero, ni
calcular la raíz de un número negativo).
c) La intersección de dos rectas (dadas las pendientes y ordenada al origen de cada recta).
Nota: validar que no sean dos rectas con la misma pendiente, antes de efectuar la operación.
"""
#a)
def obt_max_min_parabola(a,b,c):
vertice=-b/(2*a)
resultado=a*vertice*vertice
resultado=resultado+b*vertice
resultado=resultado+c
return resultado
a=3
b=2
c=0
maximo=obt_max_min_parabola(a,b,c)
print("El maximo de la parabola {0}x^2+{1}x+{2} es ==> {3}".format(a,b,c,maximo))
#b)
def raices_parabola(a,b,c):
from math import sqrt
x=[]
aux=b*b-4*a*c
aux2=0
s1=[]
s2=[]
if aux>0:
aux=sqrt(aux)
aux2=-b+aux
x.append(aux2/(2*a))
aux2=-b-aux
x.append(aux2/(2*a))
else:
if aux==0:
aux2=-b/(2*a)
x.append(aux2)
x.append(aux2)
else:
aux3=aux*(-1)
aux3=sqrt(aux3)
aux4=0
aux2=-b/(2*a)
s1.append(aux2)
aux4=aux3/(2*a)
s1.append(aux4)
aux2=-b/(2*a)
s2.append(aux2)
aux4=aux3*(-1)
aux4=aux4/(2*a)
s2.append(aux4)
x.append(s1)
x.append(s2)
return x
raices=raices_parabola(1,2,3)
print("las raices del polinomio ",raices)
| false
|
17044fe456f5ab3ea5e6d5fdb9b3bdc4b736158c
|
tskiranmayee/Python
|
/3.Functions/FuncEx.py
| 261
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 7 12:07:56 2021
@author: tskir
"""
"""Example : Add two numbers"""
def add(a,b):
c=a+b
return c
a=int(input("Enter first value:"))
b=int(input("Enter second value:"))
print("sum={}".format(add(a,b)))
| false
|
6811f8a6667506b20213934697e0b3207ace1520
|
tskiranmayee/Python
|
/5. Set&Tuples&Dictionary/AccessingItems.py
| 393
| 4.21875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 18 15:49:01 2021
@author: tskir
"""
""" Accessing Items in Dictionary """
dictEx={1:"a",2:"b",3:"c",4:"d"}
i=dictEx[1]
print("Value of the key 1 is: {}".format(i))
"""Another way of Accessing Items in Dictionary"""
j=dictEx.get(1)
print("Another way to get value for key 1 is:{}".format(j))
""" Access the keys"""
k=dictEx.keys()
print(k)
| true
|
c2e88d79e03904bc41c849691d12962c9165c683
|
Marlon-Poddalgoda/ICS3U-Assignment5-B-Python
|
/times_table.py
| 1,287
| 4.1875
| 4
|
#!/usr/bin/env python3
# Created by Marlon Poddalgoda
# Created on December 2020
# This program calculates the times table of a user input
import constants
def main():
# this function will calculate the times table of a user input
print("This program displays the multiplication table of a user input.")
print("")
# loop counter variable
loop_counter = 0
# sum of positive integers variable
answer = 0
# input
user_input = input("Enter a positive integer: ")
print("")
# process
try:
user_input_int = int(user_input)
if user_input_int > 0:
# loop statement
while loop_counter <= constants.MAX_MULTIPLICATION:
# calculations
answer = user_input_int * loop_counter
print("{0} x {1} = {2}".format(user_input_int, loop_counter,
answer))
loop_counter = loop_counter + 1
else:
# output
print("{} is not a positive integer!"
.format(user_input_int))
except Exception:
# output
print("That's not a number! Try again.")
finally:
print("")
print("Thanks for playing!")
if __name__ == "__main__":
main()
| true
|
fb976318bdc72e4137aa11b60af4d05b579fada8
|
Oleg20502/infa_2020_oleg
|
/hypots/hypot4.py
| 240
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 12:40:38 2020
@author: student
"""
import turtle
n = 1000
step = 1000/n
for i in range(n):
turtle.shape('turtle')
turtle.forward(step)
turtle.left(360/n)
| false
|
62fb9d429b269174283f7ce361fbf4b03a088308
|
PashaKim/Python-Function-Leap-year
|
/Leap-year.py
| 264
| 4.1875
| 4
|
print ("This function(is_year_leap(year)) specifies a leap year")
def is_year_leap (y):
if y%400==0:
print(y," is leap year")
elif y%4==0 and y%100!=0:
print(y," is leap year")
else:
print(y," is common year")
| false
|
ad841fe2c7b77c9f500e9a1962d9460b3dfc0425
|
sweetmentor/try-python
|
/.~c9_invoke_74p4L.py
| 2,562
| 4.3125
| 4
|
# print('Hello World')
# print('Welcome To Python')
# response = input("what's your name? ")
# print('Hello' + response)
#
# print('please enter two numbers')
# a = int(input('enter number 1:'))
# b = int(input('enter number 2:'))
# print(a + b)
# num1 = int(input("Enter First Number: "))
# num2 = int(input("Enter Second Number: "))
# total = num1 + num2
# print (str(num1))
#print(str(num1) + " plus " + str(num2) + " = " + str(total))
# print("Before the function")
# def add(x, y):
# print(x)
# print(y)
# return x + y
# print("After the function")
# print("Before calling the function")
# r = add(5, 4)
# print("After calling the function")
# print(r)
# print("After printing the result")
# text = input("what is your name:")
# text = text.upper()
# print(text)
#-------------------challenge47----
# num = int(input("please enter your number"))
# if num <= 10:
# print ("Small")
# else:
# print ("Big")
#-------------------challenge48----
# num1 = int(input("enter num1:"))
# num2 = int(input("enter num2:"))
# if num1 == num2:
# print ("Same")
# else:
# print ("Different")
#-------------challenge49-------
# num = input("enter a number:")
# if num == "1":
# name = input("please enter your name")
# print ("Your name is %s" % name)
# if num == "2":
# age = input("enter your age: ")
# age_int = int(age)
# print ("Your age is " + age)
# print("done")
#----------------------------
# i = 0
# while i < 100:
# print(i)
# i += 2
# i = 0
# while i < 100:
# print(i)
# i += 1
# i = 0
# while i < 100:
# i += 1
# print(i)
#----------------------------------
# people = {
# "Joe": 23,
# "Ann": 24,
# "Barbara": 67,
# "Pete": 55,
# "Tim": 34,
# "Sam": 13,
# "Josh": 5
# }
# name = input("Enter name: ")
# print (people[name])
#-----------------------------------
# people = {
# "Joe": {"age": 23, "eyes": "blue", "height": 134, "nationality": "Irish"},
# "Ann": {"age": 13, "eyes": "green", "height": 172, "nationality": "Irish"},
# "Bob": {"age": 23, "eyes": "red", "height": 234, "nationality": "Turkmenistan"},
# "Sam": {"age": 45, "eyes": "grey", "height": 134, "nationality": "French"},
# "Tina": {"age": 46, "eyes": "blue", "height": 154, "nationality": "American"},
# }
# name = input("Enter name: ")
# person = people[name]
# what = input("What do you want to know? ")
# print (person[what])
#--------------------------------------------
nums = []
for i in range (10)
num = int(in)
| true
|
88a00a55774274724298e6641d778fc1ef0e77d7
|
pavelgolikov/Python-Code
|
/Data_Structures/Linked_List_Circular.py
| 1,978
| 4.15625
| 4
|
"""Circular Linked List."""
class _Node(object):
def __init__(self, item, next_=None):
self.item = item
self.next = next_
class CircularLinkedList:
"""
Circular collection of LinkedListNodes
=== Attributes ==
:param: back: the lastly appended node of this CircularLinkedList
:type back: LinkedListNode
"""
def __init__(self, value):
"""
Create CircularLinkedList self with data value.
:param value: data of the front element of this circular linked list
:type value: object
"""
self.back = _Node(value)
# back.next_ corresponds to front
self.back.next = self.back
def __str__(self):
"""
Return a human-friendly string representation of CircularLinkedList self
:rtype: str
>>> lnk = CircularLinkedList(12)
>>> str(lnk)
'12 ->'
"""
# back.next_ corresponds to front
current = self.back.next
result = "{} ->".format(current.item)
current = current.next
while current is not self.back.next:
result += " {} ->".format(current.item)
current = current.next
return result
def append(self, value):
"""
Insert value before LinkedList front, i.e. self.back.next_.
:param value: value for new LinkedList.front
:type value: object
:rtype: None
>>> lnk = CircularLinkedList(12)
>>> lnk.append(99)
>>> lnk.append(37)
>>> print(lnk)
12 -> 99 -> 37 ->
"""
self.back.next = _Node(value, self.back.next)
self.back = self.back.next
def rev_print(self, current):
if current == self.back:
print(self.back.item)
else:
self.rev_print(current.next)
print(current.item)
# cl = CircularLinkedList(12)
# cl.append(13)
# cl.append(14)
# cl.rev_print(cl.back.next)
| true
|
dbaa1a417e12832ee0865031534e3d04de7e6d04
|
pavelgolikov/Python-Code
|
/Old/Guessing game.py
| 808
| 4.15625
| 4
|
import random
number = random.randint (1,20)
i=0
print ('I am thinking about a number between 1 and 20. Can you guess what it is?')
guess = int(input ()) #input is a string, need to convert it to int
while number != guess:
if number > guess:
i=i+1
print ('Your guess is too low. You used '+ str(i) + ' attempts. Try again')
guess = int(input ())
continue #Need to tell computer to return back to while loop
elif number < guess:
i=i+1 #Up the counter before reporting back
print ('Your guess is too high. You used '+ str(i) + ' attempts. Try again') #dont need to up the counter again
guess = int(input ())
continue
else:
break
i=i+1
print ('That is correct! You guessed it in ' + str (i) + ' guesses')
| true
|
9d841232854343600926341d118f977d258536be
|
pavelgolikov/Python-Code
|
/Old/Dictionary practice.py
| 1,576
| 4.1875
| 4
|
"""Some functions to practice with lists and dictionaries."""
def count_lists(list_):
"""Count the number of lists in a possibly nested list list_."""
if not isinstance(list_, list):
result = 0
else:
result = 1
for i in list_:
print(i)
result = result + (count_lists(i))
return result
def flatten_list(a, result=None):
"""Flattens a nested list.
>>> flatten_list([ [1, 2, [3, 4] ], [5, 6], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
if result is None:
result = []
for x in a:
if isinstance(x, list):
flatten_list(x, result)
else:
result.append(x)
return result
def flatten_dictionary(dic, key = '', result = None):
"""Flatten dictionary dic."""
if result is None:
result = {}
for x, y in dic.items():
if isinstance(y, dict):
flatten_dictionary(y, str(key)+str(x)+'.', result)
else:
result[str(key)+str(x)] = y
return result
def contains_satisfier(list_):
"""Check if a possibly nested list contains satisfier."""
res = False
if not isinstance(list_, list):
res = list_ > 5
else:
for el in list_:
res = res or contains_satisfier(el)
return res
def tree_reverse(lst):
lst.reverse()
list_ = []
for el in lst:
if isinstance(el, list):
list_ += [tree_reverse(el)]
else:
list_.append(el)
return list_
| true
|
3e43132819bc8bae1eb277d76ca981b9827fcde4
|
enrique95ae/Python
|
/Project 01/test007.py
| 391
| 4.1875
| 4
|
monday_temperatures = [9.1, 8.8, 7.5, 6.6, 8.9]
##printing the number of items in the list
print(len(monday_temperatures))
##printing the item with index 3
print(monday_temperatures[3])
##printing the items between index 1 and 4
print(monday_temperatures[1:4])
##printing all the items after index 1
print(monday_temperatures[1:])
##printing the last item
print(monday_temperatures[-1])
| true
|
835bbc207ec0ffb49e6a0edcf82dc3aeb3b28504
|
fbakalar/pythonTheHardWay
|
/exercises/ex26.py
| 2,999
| 4.25
| 4
|
#---------------------------------------------------------|
#
# Exercise 26
# Find and correct mistakes in someone else's
# code
#
# TODO: go back and review ex25
# compare to functions below
# make sure this can be run by importing ex25
#
#---------------------------------------------------------|
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words): #corrected mistake added ':'
"""Prints the first word after popping it off."""
word = words.pop(0) #corrected mistake poop>pop
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1) #corrected mistake added ')'
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""
print "--------------"
print poem
print "--------------"
five = 10 - 2 + 3 - 5
print "This should be five: %s" % five
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000 #corrected '\' > '/'
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point) #corrected ==:= and start-point
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) # corrected 'jeans'
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) #corrected start_pont
sentence = "All good\tthings come to those who wait." #corrected god,weight
# words = ex25.break_words(sentence)
words = break_words(sentence)
#sorted_words = ex25.sort_words(words)
sorted_words = sort_words(words)
print_first_word(words)
print_last_word(words)
print_first_word(sorted_words) #corrected
print_last_word(sorted_words)
#sorted_words = ex25.sort_sentence(sentence)
sorted_words = sort_sentence(sentence)
print sorted_words #corrected
print_first_and_last(sentence) #corrected
print_first_and_last_sorted(sentence) #corrected
| true
|
1832a289dececef43f9f2e08eaf902bc5ced7016
|
fbakalar/pythonTheHardWay
|
/exercises/ex22.py
| 1,248
| 4.1875
| 4
|
#####################################################
#
# Exercise 22 from Python The Hard Way
#
#
# C:\Users\berni\Documents\Source\pythonTheHardWay\exercises
#
#
# What do you know so far?
#
# TODO:
# add some write up for each of these
#
#####################################################
'''
this is a list of all the key words and symbols used in
exercises 1 - 21
print:
+ plus
- minus
/ slash
* asterisk
% percent
< less-than
> greater-than
<= less-than-equal
>= greater-than-equal
%s
%d
%r
True
False
binary
\t
\n
\\
raw_input()
from sys import argv
sys
argv
prompt
txt = open(filename)
print txt.read()
FILE OPERATIONS
----------------
close -- Closes the file. Like File->Save.. in your editor.
read -- Reads the contents of the file. You can assign the result to a variable.
readline -- Reads just one line of a text file.
truncate -- Empties the file. Watch out if you care about the file.
write('stuff') -- Writes "stuff" to the file.
from os.path import exists
indata = in_file.read()
len(indata)
out_file = open(to_file, 'w')
out_file.write(indata)
def print_two(*args)
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
return
'''
| true
|
d8feb89430783948201453c395aa1d4a3c1ab9d2
|
meet-projects/TEAMB1
|
/test.py
| 305
| 4.15625
| 4
|
words=["ssd","dsds","aaina","sasasdd"]
e_word = raw_input("search for a word in the list 'words': ")
check = False
for word in words:
if e_word in word or word in e_word:
if check==False:
check=True
print "Results: "
print " :" + word
if check==False:
print "Sorry, no results found."
| true
|
1b5404d371c0af7e0d3b1b48d6f517966d7f9a03
|
berchj/conditionalsWithPython
|
/condicionales.py
| 2,007
| 4.375
| 4
|
cryptoCurrency1 = input('Enter the name of the first cryptocurrency: ')
cryptoCurrencyVal1 = float(input('Enter the value of ' + str(cryptoCurrency1) + ': '))
cryptoCurrency2 = input('Enter the name of the second cryptocurrency: ')
cryptoCurrencyVal2 = float(input('Enter the value of ' + str(cryptoCurrency2) + ': '))
cryptoCurrency3 = input('Enter the name of the third cryptocurrency: ')
cryptoCurrencyVal3 = float(input('Enter the value of ' + str(cryptoCurrency3) + ': '))
if (cryptoCurrencyVal1 > cryptoCurrencyVal2 and cryptoCurrencyVal1 > cryptoCurrencyVal3) :
print(str(cryptoCurrency1) + ' : ' + str(cryptoCurrencyVal1))
if(cryptoCurrency2 > cryptoCurrency3):
print(str(cryptoCurrency2) + ' : ' + str(cryptoCurrencyVal2))
print(str(cryptoCurrency3) + ' : ' + str(cryptoCurrencyVal3))
else:
print(str(cryptoCurrency3) + ' : ' + str(cryptoCurrencyVal3))
print(str(cryptoCurrency2) + ' : ' + str(cryptoCurrencyVal2))
elif(cryptoCurrencyVal2 > cryptoCurrencyVal1 and cryptoCurrencyVal2 > cryptoCurrencyVal3):
print(str(cryptoCurrency2) + ' : ' + str(cryptoCurrencyVal2))
if(cryptoCurrencyVal1 > cryptoCurrencyVal3 ):
print(str(cryptoCurrency1) + ' : ' + str(cryptoCurrencyVal1))
print(str(cryptoCurrency3) + ' : ' + str(cryptoCurrencyVal3))
else:
print(str(cryptoCurrency3) + ' : ' + str(cryptoCurrencyVal3))
print(str(cryptoCurrency1) + ' : ' + str(cryptoCurrencyVal1))
elif(cryptoCurrencyVal3 > cryptoCurrencyVal1 and cryptoCurrencyVal3 > cryptoCurrencyVal2 ):
print(str(cryptoCurrency3) + ' : ' + str(cryptoCurrencyVal3))
if(cryptoCurrencyVal2 > cryptoCurrencyVal1):
print(str(cryptoCurrency2) + ' : ' + str(cryptoCurrencyVal2))
print(str(cryptoCurrency1) + ' : ' + str(cryptoCurrencyVal1))
else:
print(str(cryptoCurrency1) + ' : ' + str(cryptoCurrencyVal1))
print(str(cryptoCurrency2) + ' : ' + str(cryptoCurrencyVal2))
print('Thank you a lot for test this code.')
| false
|
7f9c909e6b9c0575d923b4f149f176b2f2ebb5be
|
josue-93/Curso-de-Python
|
/Py/Ejemplo8.py
| 366
| 4.25
| 4
|
#Realzar un programa que imprima en pantalla los numeros del 20 al 30
for x in range(20,31):
print(x)
'''La funcion range puede tener dos parametros, el primero indica el valor
inicial que tomara la variable x, cada vuelta del for la variable x toma
el valor siguiente hasta llegar al valor indicado por el segundo parametro
de la funcion range menos uno. '''
| false
|
63f15390b441813b85bfa8c35efa0a06db9be552
|
lachlanpepperdene/CP1404_Practicals
|
/Prac02/asciiTable.py
| 434
| 4.3125
| 4
|
value = (input("Enter character: "))
print("The ASCII code for",value, "is",ord(value),)
number = int(input("Enter number between 33 and 127: "))
while number > 32 and number < 128:
print("The character for", number, "is", chr(number))
else:
print("Invalid Number")
# Enter a character:g
# The ASCII code for g is 103
# Enter a number between 33 and 127: 100
# The character for 100 is d
| true
|
ecee3c7834b468cec5f437d173b91fc9665f63d1
|
Git-Pierce/Week8
|
/MovieList.py
| 1,487
| 4.21875
| 4
|
def display_menu():
print("MOVIE LIST MENU")
print("list - List all movies")
print("add - Add a movie")
print("del - Delete a movie")
print("exit - Exit program")
print()
def list(movie_list):
i = 1
for movie in movie_list:
print(str(i) + "- " + movie)
i += 1
print()
def add(movie_list): #mutable list
movie = input("Name: ")
movie_list.append(movie)
print(movie + " was added. \n")
def delete(movie_list):
number = int(input("Enter Movie Number: "))
if number < 1 or number > len(movie_list):
print("Invalid movie num. \n")
else:
movie = movie_list.pop(number-1)
print(movie + " was deleted. \n")
def main():
movie_list = ["Month Python",
"Lord of the Rings",
"Titanic"]
command_list = ["list", "add", "del", "exit"]
display_menu()
# code to process each choice made
#for i in range (5):
m_command = input("Enter a valid movie list menu option: ")
while m_command in command_list:
if m_command == "list":
list(movie_list)
elif m_command == "add":
add(movie_list)
elif m_command == "del":
delete(movie_list)
elif m_command == "exit":
break
else:
print("Not a valid movie list command. Try again.\n")
m_command = input("Enter a valid movie list menu option: ")
print("Movie List program ended.")
main()
| true
|
750845c87efe9e65c001c95cd24af1e9285fb40f
|
renansald/Python
|
/cursos_em_video/Desafio73.py
| 851
| 4.125
| 4
|
times = ["Plameira", "Santos", "Flamengo", "Internacional", "Atletico Mineiro", "Goiás", "Botafogo", "Bahia", "São Paulo", "Corinthias", "Grêmio", "Athlitico-PR", "Ceará SC", "Fortaleza", "Vasco da Gama", "Fluminense", "Chapecoense", "Cruzeiro", "CSA", "Avaí",];
print(f"Os 5 primeiros colocados são {times[:5]}\nOs 4 ultimos colocados são {times[16:]}\nOs times participante são {sorted(times)}\n o Chapecoense está na {times.index('Chapecoense')+1}")
print("-"*30);
print("Os primeiros são: ");
for x in range(0, 5):
print(times[x]);
print("-"*30);
print("Os quatro ultimos são: ");
for x in range(len(times) - 4, len(times)):
print(times[x]);
print("*"*30);
print(f"Times participantes do campeonato em ordem alfabetica: {sorted(times)}");
print("^"*30)
print(f"A posição da Chapecoense é {times.index('Chapecoense') + 1}");
| false
|
8129f3085e028d4cf50277d65812ff56e26f1f4e
|
renansald/Python
|
/Apostila/Capitulo2/Exercicio17.py
| 410
| 4.125
| 4
|
from math import sqrt
a = float(input("Informe o valor de \'a\': "));
b = float(input("Informe o valor de \'b\': "));
c = float(input("Informe o calor de \'c\': "));
delta = (b**2) - (4*a*c);
if(delta > 0):
print(f"As raízes são {((-b) + sqrt(delta))/(2*a)} e {((-b) - sqrt(delta))/(2*a)}");
elif(delta == 0):
print(f"Só tem uma raíz que é: {(-b)/(2*a)}");
else:
print("Número imaginário");
| false
|
1d66b04c774e3346197d17c4ca559a4c5642f3e9
|
green-fox-academy/Chiflado
|
/week-03/day-03/horizontal_lines.py
| 528
| 4.40625
| 4
|
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# create a line drawing function that takes 2 parameters:
# the x and y coordinates of the line's starting point
# and draws a 50 long horizontal line from that point.
# draw 3 lines with that function.
def drawing_horizontal_lines(x, y):
red_line = canvas.create_line(x, y, x + 50, y, fill = 'green')
drawing_horizontal_lines(110, 190)
drawing_horizontal_lines(240, 30)
drawing_horizontal_lines(69, 110)
root.mainloop()
| true
|
95908f7ea38b97f342408bbdeac0b56f276d74d5
|
green-fox-academy/Chiflado
|
/week-02/day-02/matrix.py
| 539
| 4.125
| 4
|
# - Create (dynamically) a two dimensional list
# with the following matrix. Use a loop!
#
# 1 0 0 0
# 0 1 0 0
# 0 0 1 0
# 0 0 0 1
#
# - Print this two dimensional list to the output
def matrix2d(x, y):
matrix = []
for i in range(x):
row = []
for j in range(y):
if i == j:
row.append(1)
else:
row.append(0)
matrix.append (row)
return matrix
for row in matrix2d(4, 4):
for elem in row:
print(elem, end=' ')
print()
| true
|
eccb62bc74d79af4e65142572fdb175ff1ca479d
|
green-fox-academy/Chiflado
|
/week-02/day-05/anagram.py
| 395
| 4.21875
| 4
|
first_string = input('Your first word: ')
sorted_first = sorted(first_string)
second_string = input('Aaaaand your second word: ')
sorted_second = sorted(second_string)
def anagram_finder(sorted_first, sorted_second):
if sorted_first == sorted_second:
return 'There are anagrams!'
else:
return 'There aren\'t anagrams!'
print(anagram_finder(sorted_first, sorted_second))
| true
|
6f52eeb81dedf18d2dc0b356e818818a953fcad5
|
alessandraburckhalter/python-rpg-game
|
/rpg-1.py
| 2,163
| 4.15625
| 4
|
"""In this simple RPG game, the hero fights the goblin. He has the options to:
1. fight goblin
2. do nothing - in which case the goblin will attack him anyway
3. flee"""
print("=-=" * 20)
print(" GAME TIME")
print("=-=" * 20)
print("\nRemember: YOU are the hero here.")
# create a main class to store info for all characters
class Character:
def __init__(self, health, power, name):
self.health = health
self.power = power
self.name = name
def alive(self):
if self.health > 0:
return True
else:
return False
def attack(self, enemy):
enemy.health -= self.power
return enemy.health
def print_status(self):
print(f"{self.name} has {self.health} health and {self.power} power.")
# create a main function
def main():
goblin = Character(6, 2, "Globin")
hero = Character(10, 5, "Hero")
while goblin.alive() and hero.alive():
user_input = int(input("\nWhat do you want to do?\n1. fight goblin\n2. do nothing\n3. flee\n> "))
# Print hero and goblin status after each user input
hero.print_status()
goblin.print_status()
if user_input == 1:
# Hero attacks goblin
hero.attack(goblin)
if not hero.alive():
print("\nYou are dead.")
if goblin.health > 0:
# Goblin attacks hero
goblin.attack(hero)
if not goblin.alive():
print("\nGoblin is dead.")
if goblin.alive():
print("\nGoblin still in the game. Watch out.")
elif user_input == 2:
# Hero does nothing, but Goblin still attacking
goblin.attack(hero)
print("\nOops. Goblin has attacked you! Fight back!")
if not goblin.alive():
print("\nGoblin is dead.")
if not hero.alive():
print("\nYou are dead. Too late to fight back :(")
elif user_input == 3:
print("\nGoodbye.")
break
else:
print("\nInvalid input %r" % user_input)
main()
| true
|
88561d8cc5a2b0a3778877fbf87a05d0a378d21d
|
gssasank/UdacityDS
|
/DataStructures/LinkedLists/maxSumSubArray.py
| 805
| 4.25
| 4
|
def max_sum_subarray(arr):
current_sum = arr[0] # `current_sum` denotes the sum of a subarray
max_sum = arr[0] # `max_sum` denotes the maximum value of `current_sum` ever
# Loop from VALUE at index position 1 till the end of the array
for element in arr[1:]:
'''
# Compare (current_sum + element) vs (element)
# If (current_sum + element) is higher, it denotes the addition of the element to the current subarray
# If (element) alone is higher, it denotes the starting of a new subarray
'''
current_sum = max(current_sum + element, element)
# Update (overwrite) `max_sum`, if it is lower than the updated `current_sum`
max_sum = max(current_sum, max_sum)
return max_sum
# FLAGGED
| true
|
562547cb28e651432ca6be189ebd212e0ba50d31
|
gssasank/UdacityDS
|
/PythonBasics/conditionals/listComprehensions.py
| 784
| 4.125
| 4
|
squares = [x**2 for x in range(9)]
print(squares)
#if we wanna use an if statement
squares = [x**2 for x in range(9) if x % 2 == 0]
print(squares)
#if we wanna use an if..else statement, it goes in the middle
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]
print(squares)
# QUESTIONS BASED ON THE CONCEPT
#Q1
names = ["Rick Sanchez", "Morty Smith", "Summer Smith", "Jerry Smith", "Beth Smith"]
first_names =[name.split()[0].lower() for name in names]
print(first_names)
#Q2
multiples_3 = [num for num in range(3,63) if num%3 == 0]
print(len(multiples_3))
#Q3
scores = {
"Rick Sanchez": 70,
"Morty Smith": 35,
"Summer Smith": 82,
"Jerry Smith": 23,
"Beth Smith": 98
}
passed = [key for key, value in scores.items() if value>=65]
print(passed)
| true
|
e6908a1fede2583910d752dec6b6af8ddf2a0460
|
gssasank/UdacityDS
|
/PythonBasics/functions/scope.py
| 483
| 4.1875
| 4
|
egg_count = 0
def buy_eggs():
egg_count += 12 # purchase a dozen eggs
buy_eggs()
#In the last video, you saw that within a function, we can print a global variable's value successfully without an error.
# This worked because we were simply accessing the value of the variable.
# If we try to change or reassign this global variable, however, as we do in this code, we get an error.
# Python doesn't allow functions to modify variables that aren't in the function's scope.
| true
|
006dc8d3d41608e3ecee53ef09350e01428e5f82
|
faizjamil/learningally-summer-coding-workshop
|
/helloWorld.py
| 285
| 4.15625
| 4
|
#!/usr/bin/python3
# prints 'hello world'
print('hello world')
# var for name
name = 'Faizan'
#print 'hello' + name
print('Hello ' + name)
# loop and print 'hello' + name
for i in range(0, 5):
if (i % 2 == 0):
print('hello world')
else:
print('Hello ' + name)
| false
|
9d5ffed0062bed15ae172ae26589eb30fee2e74f
|
JeahaOh/Python_Study
|
/Do_It_Jump_To_Python/1_Basic/02_Type/02_String/03_IndexingSlicing.py
| 1,377
| 4.25
| 4
|
# 문자열의 인덱스와 잘라내기
ㅁ = 'Life is too short, You need Python.'
print(ㅁ)
print('ㅁ -7 : ' + ㅁ[-7])
# 문자열 슬라이싱.
b = ㅁ[0:4]
print('ㅁ[0:4] : ' + b)
'''
문자열 슬라이싱은
문자열[시작 idx : 끝 idx]으로, 끝 인덱스는 포함하지 않는다.
시작 idx <= 대상 문자열 < 끝 idx
'''
# 끝 idx를 생략하면 문자열의 끝까지 뽑아낸다.
print('ㅁ[19:] : ' + ㅁ[19:])
# 시작 idx를 생략하면 처음부터 끝까지 뽑아낸다.
print('ㅁ[:19] : ' + ㅁ[:19])
# 양쪽 idx 를 생랼하면 문자열의 처음부터 끝까지 뽑아낸다.
print('ㅁ[:] : ' + ㅁ[:])
# -idx 를 사용할 수 있다. 역시 ㅁ[-7]은 포함하지 않는다.
print('ㅁ[19:-7] : ' + ㅁ[19:-7])
print('=' * 20)
## 슬라이싱으로 문자열 나누기
a = '20190827Sunny'
date = a[:8]
weather = a[8:]
print('a : ' + a)
print('data : ' + date)
print('weather : ' + weather)
print('=' * 20)
year = a[:4]
date = a[4:8]
weather = a[8:]
print('a : ' + a)
print('year : ' + year)
print('data : ' + date)
print('weather : ' + weather)
print('=' * 20)
'''
Python의 String은 immutable한 자료형 이라고 함.
이는 문자열의 요솟값을 변경할 수 없기 때문임.
문자열의 요소를 바꾸려면 슬라이싱 기법을 사용해서 해야 함.
'''
a = 'pithon'
a = a[:1] + 'y' + a[2:]
print(a)
| false
|
188bd91cfa5302a8cc99c2f09e4aa376c35895b7
|
gredenis/-MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
|
/ProblemSet1/Problem3.py
| 1,187
| 4.25
| 4
|
# Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example,
# if s = 'azcbobobegghakl', then your program should print
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
# Longest substring in alphabetical order is: abc
# Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem,
# we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had
# a break and cleared your head.
temp = ''
longest = ''
number = 0
while True:
if number == len(s):
break
elif temp == '':
temp = s[number]
number += 1
elif s[number] >= s[number - 1]:
temp = temp + s[number]
number += 1
if len(temp) > len(longest):
longest = temp
else:
if len(temp) > len(longest):
longest = temp
temp = ''
else:
temp = ''
print(longest)
| true
|
19d990ea9b35b7224bef4f99aa49bee947abd4ef
|
dejoker95/baekjoon
|
/기초/11729.py
| 234
| 4.125
| 4
|
def hanoi(n, start, dest, other):
if n < 2:
print(start, dest)
return
hanoi(n-1, start, other, dest)
print(start, dest)
hanoi(n-1, other, dest, start)
n = int(input())
print((2**n)-1)
hanoi(n, 1, 3, 2)
| false
|
ec72975409e3eda6707fcb67778244299c00431e
|
Rhotimie/ZSSN
|
/lib/util_sort.py
| 1,361
| 4.125
| 4
|
import itertools
def sort_tuple_list(tuple_list, pos, slice_from=None):
"""
Return a List of tuples
Example usage:
sort_tuple_list([('a', 1), ('b', 3), ('c', 2)])
:param status: list of tuples
:type status: List
:param list:
:param int:
:return: sorted list of tuples e.g [('a', 1), ('c', 2) ('b', 3)] usig element at pos 1 to sort
"""
if tuple_list and type(tuple_list) == list:
if pos >= len(tuple_list[0]): return None
slice_from = len(tuple_list) if not slice_from else slice_from
return sorted(tuple_list, key = lambda i: i[pos], reverse = True)[:slice_from]
return []
def grouper(n, iterable, is_fill=False, fillvalue=None):
"""
split a list into n desired groups
Example
list(grouper(3, range(9))) = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
:return: list of tuples
"""
args = [iter(iterable)] * n
if is_fill:
return list(itertools.zip_longest(*args, fillvalue=fillvalue))
else:
return list([e for e in t if e != None] for t in itertools.zip_longest(*args))
def un_grouper(list_of_lists):
"""
combines a list of lists into a single list
Example
grouper([(0, 1, 2), (3, 4, 5), (6, 7, 8)]) = list(range(9))
:return: list of tuples
"""
return list(itertools.chain.from_iterable(list_of_lists))
| true
|
b445be9fa502014837bbc795a20d74940eb7d72d
|
NotBobTheBuilder/conways-game-of-life
|
/conways.py
| 2,242
| 4.125
| 4
|
from itertools import product
from random import choice
def cells_3x3(row, col):
"""Set of the cells around (and including) the given one"""
return set(product(range(row-1, row+2), range(col-1, col+2)))
def neighbours(row, col):
"""Set of cells that directly border the given one"""
return cells_3x3(row, col) - {(row, col)}
class CGOL(object):
"""Iterator representing the generations of a game"""
def __init__(self, grid):
"""
Takes a 2d list of bools as a grid which is used to create
internal representation of game state (a set of living coordinates)
"""
self.cells = {(row_i, col_i) for row_i, row in enumerate(grid)
for col_i, alive in enumerate(row)
if alive}
def __iter__(self):
"""Iterator progressing through each round until all cells are dead"""
yield self
while self.cells:
self.cells = set(filter(self.cell_survives, self.cells_to_check()))
yield self
def __str__(self):
"""Represent the round as a 2d grid of + or . for alive or dead"""
return '\n'.join(''.join('+' if self.cell_alive((r, c)) else '.'
for c in range(20)) for r in range(20))
def cell_alive(self, cell):
"""Checks if the given cell is alive or dead"""
return cell in self.cells
def cell_survives(self, cell):
"""Checks if the given cell makes it to the next generation"""
neighbours = self.neighbour_count(*cell)
return neighbours == 3 or neighbours == 2 and self.cell_alive(cell)
def neighbour_count(self, row, col):
"""Number of living neighbours surrounding the given cell"""
return len(set(filter(self.cell_alive, neighbours(row, col))))
def cells_to_check(self):
"""Cells which could be alive in the next generation"""
return {border for cell in self.cells for border in cells_3x3(*cell)}
if __name__ == "__main__":
game = CGOL([[choice([True, False]) for r in range(20)] for c in range(20)])
for round, grid in zip(range(40), game):
print("===== round {} =====".format(round))
print(grid)
| true
|
1db2a4fbd6827d302d3adb1562911e404b3ed2f5
|
EvgeniiGrigorev0/home_work-_for_lesson_2
|
/Lesson_3/HW_2_Lesson_3.py
| 1,162
| 4.125
| 4
|
# 2. Реализовать функцию, принимающую несколько параметров,
# описывающих данные пользователя: имя, фамилия, год рождения,
# город проживания, email, телефон. Функция должна принимать
# параметры как именованные аргументы. Реализовать вывод
# данных о пользователе одной строкой.
...
name = input('Введите ваше имя: ')
surname = input('Введите фамилию: ')
date_of_birthday = input('Введите год вашего рождения: ')
city = input('Введите ваш город проживания')
email = input('Введите вашу электронную почту: ')
mobile_phone = input('Введите ваш теелфон: ')
...
def info_of_person(name, surname, date_of_birthday, city, email, mobile_phone):
return ' '.join(
[name, surname, date_of_birthday, city, email, mobile_phone])
print(info_of_person(name, surname, date_of_birthday, city, email, mobile_phone))
| false
|
c5b638d3bb9940c3d92c8d1f5bb6616b0244256d
|
emir-naiz/first_git_lesson
|
/Courses/1 month/3 week/day 5/Задача №1.py
| 344
| 4.28125
| 4
|
# Программа имеет список и выводит список из 3 элементов:
# первого, третьего и второго с конца элементов.
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = []
list2.append(list1[0])
list2.append(list1[2])
list_len = len(list1)
list2.append(list1[list_len-2])
print(list2)
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.