blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0b9b8fe6fabd72a052c5317ff141064693f21d96 | erikaosgue/python_challenges | /easy_challenges/16-minimun_by_key.py | 984 | 4.40625 | 4 | #!/usr/bin/python3
# As a part of this problem, we're going to build, piece-by-piece,
# the part of a relational database that can take a list of rows and
# sort them by multiple fields:
# i.e., the part that implements
# ORDER BY name ASC, age DESC
# Step 1: we want to write a function that returns the record
# with the smallest entry of a given key
#
# Treat missing keys as 0
def min_by_key(arr, key):
min_val = arr[0]
for dict_ in records:
if key in dict_ :
if key in min_val:
if dict_[key] < min_val[key]:
min_val = dict_
elif min_val[key] > 0 :
min_val = dict_
return min_val
records = [
{'a': 1, 'b': 4},
{'a': 3, 'b': 1},
{'a': 2},
{'a': -2, 'b': 2},
{'b': 3}
]
print('min_by_key')
print(min_by_key(records, 'a')) # -> {a: -2, b: 2}
print(min_by_key(records, 'b')) # -> {a: 2}, since we treat b as 0
| true |
7bf8176a07d3a2573cc4047176e80da80944baec | ThomasSessions/Rock-Paper-Scissors | /RPSgame.py | 2,369 | 4.53125 | 5 | # Rock, paper, scissors game B05:
from random import randint # Allows the generation of random numers, "randint" means random integer
# Lets define some values
player_score = 0
computer_score = 0
x = player_score
y = computer_score
# Using a dictionary with winning results makes for a much cleaner results section.
Outcomes = {'Rock':'Scissors',
'Paper':'Rock',
'Scissors':'Paper'
}
# Here were set the name of the while loop and set it's value to 0, we add 1 each time the loop runs until it gets to 4 where the loops ends.
Best_of_five = 0
while Best_of_five <= 4:
Best_of_five += 1
# Here we add a prompt for the player to input a value, rememeber \n just makes the code start on a new line.
player = input("\nRock, Paper or Scissors? :")
print(player, "\nVs.")
# The players input is printed and then the computer is asked to pick a number between 1 and 3. These numbers are given values and those values are printed.
chosen = randint(1, 3)
if chosen == 1:
computer = "Rock"
elif chosen == 2:
computer = "Paper"
else:
computer = "Scissors"
print(computer)
# This section determines what results we get from the input. If the input from the player and computer are the same its a draw.
# The "Outcomes" dictionary holds the possible winning combinations for the player. What is left over will be losing combinations for the player.
# Points are awarded to who wins anda running tally is kept. The current scores are also printed.
if player == computer:
print("\nTie \nComputer: " + str(y) + " Player: " + str(x))
elif Outcomes.get(player) == computer:
x += 1
print("\nYou win! \nComputer: " + str(y) + " Player: " + str(x))
else:
y += 1
print("\nComputer wins! \nComputer: " + str(y) + " Player: " + str(x))
# Once there have been 5 loops of the game this else statement will figure out the winner through a series of greater than or less than statements.
# Remember that "x" is the player and "y" is the computer and depending on who wins the rounds one point is added.
else:
if x > y:
print("\nWINNER WINNER CHICKEN DINNER!")
elif y > x:
print("\nBETTER LUCK NEXT TIME, SKYNET WINS!")
else:
print("\nITS A DRAW!")
| true |
ee2a377708e520e9f316eefcb10665f07d4b816b | Zakir44/Assignment.4 | /04.py | 203 | 4.125 | 4 | #Accept number from user and calculate the sum of all number from 1 to a given number
a = int(input("Enter The Value: "))
SUM = 0
for i in range(a, 0, -1):
SUM = SUM+i
print("Sum :", SUM)
| true |
310f09091114e7e0068f092a986cb8021891fa80 | jalondono/holbertonschool-machine_learning | /math/0x05-advanced_linear_algebra/0-determinant.py | 1,270 | 4.125 | 4 | #!/usr/bin/env python3
"""Determinant"""
def check_shape(matrix):
"""
Check if is a correct matrix
:param matrix: matrix list
:return:
"""
if len(matrix):
if not len(matrix[0]):
return 3
if not isinstance(matrix, list) or len(matrix) == 0:
return 2
for row in matrix:
if len(row) != len(matrix):
return 1
if not isinstance(row, list):
return 2
return 0
def determinant(matrix):
"""
that calculates the determinant of a matrix:
:param matrix:
:return:
"""
if check_shape(matrix) == 3:
return 1
if check_shape(matrix) == 2:
raise TypeError("matrix must be a list of lists")
if check_shape(matrix) == 1:
raise ValueError("matrix must be a square matrix")
if len(matrix) == 1:
return matrix[0][0]
if len(matrix) == 2:
a = matrix[0][0]
b = matrix[0][1]
c = matrix[1][0]
d = matrix[1][1]
return (a*d) - (b*c)
det = 0
for idx, data in enumerate(matrix[0]):
rows = [row for row in matrix[1:]]
n_m = [[val for i, val in enumerate(row) if i != idx] for row in rows]
det += data * (-1) ** idx * determinant(n_m)
return det
| true |
b31231c2ef1775c518afe43afd92db7d235df346 | jalondono/holbertonschool-machine_learning | /supervised_learning/0x00-binary_classification/0-neuron.py | 840 | 4.125 | 4 | #!/usr/bin/env python3
""" Neuron """
import numpy as np
class Neuron:
"""Neuron Class"""
def __init__(self, nx):
"""
constructor method
nx is the number of input features to the neuron
"""
if not isinstance(nx, int):
raise TypeError('nx must be an integer')
if nx < 1:
raise ValueError('nx must be a positive integer')
"""
W = The weights vector for the neuron. Upon instantiation
using a random normal distribution.
"""
self.W = np.random.normal(0, 1, (1, nx))
"""The bias for the neuron. Upon instantiation, it should be initialized to 0."""
self.b = 0
"""The activated output of the neuron (prediction).
Upon instantiation, it should be initialized to 0."""
self.A = 0
| true |
0e10d0d6502e8acb640f20d509ec37ea9319b9d5 | bpbpublications/Advance-Core-Python-Programming | /Chapter 02/section_2_2.py | 783 | 4.15625 | 4 | class Students:
student_id = 50
# This is a special function that Python calls when you create new instance of the class
def __init__(self, name, age):
self.name = name
self.age = age
Students.student_id = Students.student_id + 1
print('Student Created')
# This method keeps a count of total number of students
def Total_no_of_students(self):
print("Total Number of students in the school are : "+str(Students.student_id))
def __del__(self):
print('object {} life cycle is over. '.format(self.name))
# create an object stu1
stu1 = Students('Paris', 12)
stu1.Total_no_of_students()
# destroy object stu1
del stu1
#Checking if the object still exists
stu1.Total_no_of_students()
| true |
5531feb525cabab21c61164afec1eba78ef088ce | bpbpublications/Advance-Core-Python-Programming | /Chapter 02/section2_1.py | 2,502 | 4.4375 | 4 | ### All code boxes of section 2.1 Classes and Objects
class Employee:
def __init__(self, name, email, department, age, salary):
self.name = name
self.email = email
self.department = department
self.age = age
self.salary = salary
#####
class Employee:
def __init__(self, a, b, c, d, e):
self.name = a
self.email = b
self.department = c
self.age = d
self.salary = e
##########
class Employee:
def __init__(self, name, email, department, age, salary):
self.name = name
self.email = email
self.department = department
self.age = age
self.salary = salary
e1 = Employee("Alex","alex@company_name.com","Finance",42,500000)
###########
def print_employee(self):
print("Name : ",self.name)
print("Email : ",self.email)
print("Department : ",self.department)
print("Age : ",self.age)
print("Salary : ",self.salary)
##########
e1.print_employee()
#############
class Employee:
def __init__(self, name, email, department, age, salary):
self.name = name
self.email = email
self.department = department
self.age = age
self.salary = salary
def print_employee(self):
print("Name : ",self.name)
print("Email : ",self.email)
print("Department : ",self.department)
print("Age : ",self.age)
print("Salary : ",self.salary)
e1 = Employee("Alex","alex@company_name.com","Finance",42,500000)
e1.print_employee()
####################
class Employee:
def __init__(self, name, email, department, age, salary):
self.name = name
self.email = email
self.department = department
self.age = age
self.salary = salary
def print_employee(self):
print("Name : ",self.name)
print("Email : ",self.email)
print("Department : ",self.department)
print("Age : ",self.age)
print("Salary : ",self.salary)
e1 = Employee("Alex","alex@company_name.com","Finance",42,500000)
e1.print_employee()
e2 = Employee("Evan","evan@company_name.com","HR",34,300000)
e2.print_employee()
e3 = Employee("Maria","maria@company_name.com","HR",30,350000)
e3.print_employee()
e4 = Employee("Pradeep","pradeep@company_name.com","IT",28,700000)
e4.print_employee()
e5 = Employee("Simon","simon@company_name.com","Finance",40,500000)
e5.print_employee()
e6 = Employee("Venkatesh","venkatesh@company_name.com","Sales",25,200000)
e6.print_employee()
| false |
34965ac46691239e08b86dab83ee6b52929c9900 | palani19/thilopy | /12.py | 220 | 4.15625 | 4 | a=int(input("Enter a value for a"))
b=int(input("Enter a value for b"))
#comparing no.
if(a>b):
print(a,"is greater than ",b)
elif(a==b):
print(a,"is equal to",b)
elif(b>a):
print(a,"is greater than",b) | true |
ccd1f00eea5df48e73e66af0f9a15ca86f1b82bb | xiaoqiangjava/python-algorithm | /learn/101.py | 1,865 | 4.21875 | 4 | #!/usr/bin/python
# -*- encoding: utf-8 -*-
from tree import TreeNode
# 对称二叉树
class Solution:
@staticmethod
def isSymmetric(root: TreeNode) -> bool:
"""
迭代实现: 按照左节点的左节点与右节点的右节点进行比较,左节点的右节点跟右节点的左节点进行比较的规则
按照次序将节点入队,出队时比较两个节点的值是否相同,或者两个都为None
"""
if not root:
return True
if not root.left and not root.right:
return True
queue = [root.left, root.right]
while queue:
left = queue.pop(0)
right = queue.pop(0)
if not left and not right:
continue
if not left or not right:
return False
if left.val != right.val:
return False
queue.append(left.left)
queue.append(right.right)
queue.append(left.right)
queue.append(right.left)
return True
def isSymmetric1(self, root: TreeNode) -> bool:
"""
迭代实现
"""
if not root:
return True
return self.symmetric(root.left, root.right)
def symmetric(self, left: TreeNode, right: TreeNode) -> bool:
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return self.symmetric(left.left, right.right) and self.symmetric(left.right, right.left)
if __name__ == '__main__':
node = TreeNode.TreeNode(1)
node.left = TreeNode.TreeNode(2)
node.right = TreeNode.TreeNode(2)
node.left.right = TreeNode.TreeNode(3)
node.right.right = TreeNode.TreeNode(3)
print(Solution.isSymmetric(node))
| false |
37735d424718aaab2db2dab0956cef77fb8b51fd | rvmoura96/exercicios-aleatorios | /Collatz/collatz.py | 1,248 | 4.21875 | 4 | """Enunciado do exercício.
Analisando a conjectura de Collatz
Você está resolvendo este problema.
Este problema foi utilizado em 223 Dojo(s).
Para definir uma seqüência a partir de um número inteiro o positivo, temos as seguintes regras:
n → n/2 (n é par)
n → 3n + 1 (n é ímpar)
Usando a regra acima e iniciando com o número 13, geramos a seguinte seqüência:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
Podemos ver que esta seqüência (iniciando em 13 e terminando em 1) contém 10 termos. Embora ainda não tenha sido provado (este problema é conhecido como Problema de Collatz), sabemos que com qualquer número que você começar, a seqüência resultante chega no número 1 em algum momento.
Desenvolva um programa que descubra qual o número inicial entre 1 e 1 milhão que produz a maior seqüência.
"""
def check_collatz(number):
if number % 2 != 0:
return (number * 3) + 1
return number // 2
def collatz_sequence(number):
sequence = [number]
new_number = number
while new_number != 1:
new_number = check_collatz(new_number)
sequence.append(new_number)
return sequence
def collatz_sequence_len(number):
return len(collatz_sequence(number))
| false |
5f8b0aa422823da65f7d147ec85a0b3901f73982 | galenscovell/Project-Euler | /Python/Euler02.py | 736 | 4.1875 | 4 |
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
# Personal challenge: Find sum of even or odd value terms up to given input value.
limit = int(input('Find sum of fibonacci sequence to which value? > '))
evenSum = []
oddSum = []
fibonacci = []
n1, n2 = 0, 1
fibonacci.append(n1)
fibonacci.append(n2)
while n1 <= limit:
n1, n2 = n2, n1 + n2
fibonacci.append(n2)
limit -= 1
for i in fibonacci:
if i % 2 == 0:
evenSum.append(i)
else:
oddSum.append(i)
print('Even Sum: ' + sum(evenSum))
print('Odd Sum: ' + sum(oddSum))
| true |
b6b971560131267695b3f5a055f2dabd972e60cf | Python-Geek-Labs/learn-python- | /tut5 - dictionary, dict. function.py | 581 | 4.21875 | 4 | # Dictionary is nothing but key value pairs
d1 = {}
# print(type(d1))
d2 = {"Harry":"Burger",
"Rohan":"Fish",
"SkillF":"Roti",
"Shubham":{"B":"maggie", "L":"roti", "D":"Chicken"}}
# d2["Ankit"] = "Junk Food"
# d2[420] = "Kebabs"
# print(d2)
# del d2[420]
# print(d2["Shubham"])
# below code will not create a new d3
# if u remove something from d3, it will also be removed from d2
d3 = d2
# now this code will create new d3 as a copy of d2
d3 = d2.copy()
del d3["Harry"]
print(d2.get('Harry'))
d2.update({"Leena":"Toffee"})
print(d2.keys())
print(d2.items())
| false |
3a299e5a203d3d4e54d2e92e06ed4d8c82c8c35d | Python-Geek-Labs/learn-python- | /tut16 - functions and docstrings.py | 695 | 4.21875 | 4 | # Built-In function (pre-defined fucntions)
# for eg - sum(param) where param must be an iterable var
# like list, tuple, set
# c = sum((9, 8)) or c = sum([9, 8]) or c = sum({9, 8})
def func():
print('Hello, u are in function')
func() # only print the hello statement
print(func()) # print hello statement and return None
# this line will also call function and print the statement
# but if u had only returned the value then the value would have stored in the variable
a = func()
def add(a, b):
'''This is a function which calculate average of two numbers'''
return (a+b)/2
x = add(5, 7)
print(x)
print(add.__doc__) # first multiline comment in a function is a DocString | true |
69773915f28a21e255badc11e9288ab18b914483 | Python-Geek-Labs/learn-python- | /tut7 - set, set functions.py | 1,237 | 4.1875 | 4 | s = set()
print(s)
# s = set(1, 2, 3, 4, 5) ----> Wrong !!
s = set([1, 2, 3, 4, 5, 10]) # ----> Right :)
# print(type(s))
l = [1, 2, 3, 4, 4]
setFromList = set(l)
print(setFromList)
print(type(setFromList))
print(len(s))
print(min(s))
print(max(s))
s.add(6)
s.remove(10)
print(s)
newSet = {2, 3, 45, 'hello cool dudes'}
s.union(newSet)
s.intersection(newSet)
s_newSet_union = s.union(newSet)
s_newSet_intersection = s.intersection(newSet)
s_newSet_difference = s.difference(newSet)
print(s_newSet_union)
print(s_newSet_intersection)
print(s_newSet_difference)
print(s.isdisjoint(newSet))
''' Remember, True === 1
False === 0
if you add True or False in a set
and there is 1 or 0 already present in the set
then True or False would be skipped
Because in Python 1 == True (and hash(1) == hash(True)) and you have 1 in your set already.
Imagine this example:
example1 = {0, False, None}
example2 = {1, True}
print(example1)
print(example2)
Will output:
{0, None}
{1}
First set has 0 and None because 0 == False but 0 != None. With second set 1 == True so True isn't added to the set.
Proof :
https://stackoverflow.com/questions/51505826/how-come-i-can-add-the-boolean-value-false-but-not-true-in-a-set-in-python
''' | true |
265289d883461b3a23dc756e1044a9eefa62ec3e | Techie1212/myprograms | /practice13.py | 339 | 4.1875 | 4 | number=int(input("enter input:"))
result1=5*(number*number)+4
result2=5*(number*number)-4
Number1=result1
Number2=result2
number1=int(Number1**0.5)
number2=int(Number2**0.5)
if(number1*number1==Number1 or number2*number2==Number2):
print(f"'{number}' is fibonacci number")
else:
print(f"'{number}'is not fibonacci number")
| false |
8c31921e9ee9391f6088bff58c1ed556ef910f5d | muskan1301/PyProjects | /sps.py | 983 | 4.125 | 4 | import random
print("Rules")
print("stone vs paper -> paper ")
print("stone vs Scissor -> stone ")
print(" Scissor vs paper -> Scissor ")
n = "Continue"
computer = 0
user = 0
l1 = ['stone','paper','scissor']
while(n == 'Continue'):
i = input("Please Enter your choice:")
a = random.choice(l1)
print("Computer's choice is ",a)
if (a == 'stone' and i == 'paper') or (a == 'paper' and i == 'scissor') or (a=='scissor' and i == 'stone'):
print("You won")
user = user+1
if (a == 'paper' and i == 'stone') or (a == 'scissor' and i == 'paper') or (a=='stone' and i == 'scissor'):
print("Computer Won")
computer += 1
if (a == i):
print("Tie")
n = input("Enter Continue to Continue:")
if computer > user:
print("Computer won by ", computer ,"-",user ,"points")
if computer < user:
print("You won by ", user ,"-", computer,"points")
if computer == user:
print("It's a tie ", user ,"-", computer,"points") | false |
3a489ad75cbae06ce788c1acf29103630a841b83 | ohduran/problemsolvingalgorithms | /LinearStructures/Queue/hotpotato.py | 592 | 4.125 | 4 | from queue import Queue
def hot_potato(names, num):
"""
Input a list of names,
and the num to be used for counting.
It returns the name of the last person
remaining after repetitive counting by num.
Upon passing the potato, the simulation
will deque and immediately enqueue that person.
"""
q = Queue()
for name in names:
q.enqueue(name)
count = 0
while q.size() > 1:
top = q.dequeue()
if count == num:
count = 0
else:
count += 1
q.enqueue(top)
return q.dequeue()
| true |
1f3963d9ac195ac26cc3c4129f719f66a5cc37bc | ohduran/problemsolvingalgorithms | /Trees and Tree Algorithms/trees.py | 1,652 | 4.1875 | 4 | """Tree Data Structures."""
class BinaryTree():
"""A Binary Tree is a Tree with a maximum of two children per node."""
def __init__(self, key):
"""Instantiate a Binary Tree."""
self.key = key
self.left_child = None
self.right_child = None
def get_left_child(self):
"""Return the binary tree corresponding to the left child of node."""
return self.left_child
def get_right_child(self):
"""Return the binary tree corresponding to the right child of node."""
return self.right_child
def set_root_value(self, value):
"""Store the object value in root."""
self.key = value
def get_root_value(self):
"""Return the object stored in node."""
return self.key
def insert_left(self, node):
"""
Create a new Binary Tree and install as the left child of node.
If a left child already exists,
it will become the left child of the new node.
"""
if self.left_child is None:
self.left_child = BinaryTree(node)
else:
bt = BinaryTree(node)
bt.left_child = self.left_child
self.left_child = bt
def insert_right(self, node):
"""
Create a new Binary Tree and install as the right child of node.
If a right child already exists,
it will become the right child of the new node.
"""
if self.right_child is None:
self.right_child = BinaryTree(node)
else:
bt = BinaryTree(node)
bt.right_child = self.right_child
self.right_child = bt
| true |
0bc39ebe68a11c02e724e50f4af7cdada6e47628 | hyperc54/ml-snippets | /supervised/linear_models/linear_regression.py | 1,644 | 4.28125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 13:17:51 2018
This example is about using Linear Regression :
- in 1D with visualisation
- in ND
Resources
Trying to understand the intercept value :
http://blog.minitab.com/blog/adventures-in-statistics-2/regression-analysis-how-to-interpret-the-constant-y-intercept
@author: pierre
"""
#%% Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import datasets
#%% Load data
diabetes = datasets.load_diabetes()
boston = datasets.load_boston()
#%% Global parameters
dataset = boston
low_d = True # Turn off/on to work in 1D or ND
#%% Select data in case of low_d
if low_d:
# Col 2 is nice for diabetes, and 5 for boston
final_data = dataset.data[:, 5]
else:
final_data = dataset.data
#%% Visualise if low-D
if low_d:
plt.scatter(final_data, dataset.target)
#%% Perform linear regression
lr = linear_model.LinearRegression()
lr.fit(final_data.reshape(-1,1), dataset.target)
#%% Generate
predictions = lr.predict(final_data.reshape(-1,1))
#%% Evaluate
print("R2 score")
print(lr.score(final_data.reshape(506,1), dataset.target))
print(" or:")
print(r2_score(dataset.target, predictions))
print("\n")
print("Coefficients :")
print(lr.intercept_)
print(lr.coef_)
print("\n")
print("MSE")
print(mean_squared_error(dataset.target, predictions))
#%% Visualise
if low_d:
plt.scatter(final_data, dataset.target, color='black')
plt.plot(final_data, predictions, color='blue', linewidth=3)
| true |
bc91c6f05a549c07334497025e8329e558d306a2 | leemarreros/coding-challenges-explained | /max-sum-of-pyramid/pyramid-reduce-solution.py | 998 | 4.25 | 4 | from functools import reduce
# The returned value of 'back_slide' will become 'prev_array'
# in the next iteration.
# At first, we only take the last two arrays of 'pyramid'.
# After we calculate the greatest path between those two
# arrays, that same result is represented by 'prev_array'
# and computed again
# The 'reduce' method will keep iterating from left to right
# over all elements of 'pyramid'
def back_slide(last_array, prev_array):
return [
prev_array[i] + max(last_array[i], last_array[i + 1])
# Once we have two arrays of 'pyramid' we iterate over
# the above array from left to right.
for i in range(len(prev_array))
]
def longest_slide_down(pyramid):
# 'reversed' method reverses 'pyramid'. Required since
# 'reduce' method goes from left to right.
# Since all elements of 'pyramid' are arrays, reduce also
# will produce an array. Its first value is obtained via [0].
return reduce(back_slide, reversed(pyramid))[0]
| true |
e5a0042d0114448f9bf78e10b74e86778c73afcb | qalp34/100DaysOfCode | /week06/Day38.py | 243 | 4.1875 | 4 | cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
cars = ["Ford", "Volvo", "BMW"]
cars.append("honda")
print(cars)
cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)
| false |
85725c7b415e438578303cc522456b9fdb0f020d | Nishimirwe/python-algorithms | /src/interview_questions/recursionAndDynamicProgramming/easy/flatten.py | 558 | 4.1875 | 4 | # Flatten --> write a recursion function called flatten
# which accepts an array of arrays and returns a new array with all the values flattened
def flatten(arr):
resultArr = []
for custItem in arr:
if type(custItem) is list:
resultArr.extend(flatten(custItem))
else:
resultArr.append(custItem)
return resultArr
dtSet0 = [1,2,3,4,5]
dtSet1 = [1,2,3,[4,5]]
dtSet2 = [1,[2,[3, 4], [[5]]]]
dtSet3 = [[[1,[[[2]]], [[[[[[[3]]]]]]]]]]
print(flatten(dtSet1))
print(flatten(dtSet2))
print(flatten(dtSet3))
| true |
fa1f73a816833b275067a434c25e5f7362eeb9ce | Nishimirwe/python-algorithms | /src/interview_questions/recursionAndDynamicProgramming/hard/robot_in_a_grid.py | 2,263 | 4.21875 | 4 | #Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
#The robot can only move in two directions, right and down, but certain cells are "off limits"
#such that the robot cannot step on them. Design an algorithm to find a path for the
#robot from the top left to the bottom right.
def callGetPath(rows, cols):
assert rows and cols > 0
grid = [[False for i in range(cols)] for j in range(rows)]
path = [];
if( getPath(grid, len(grid)-1, len(grid[0])-1, path) ):
return path
return None
def getPath(grid, row, col, path):
if( row < 0 or col < 0 or (grid[row][col] == True)):
return False
isAtOrigin = (row == 0) and (col == 0)
if(isAtOrigin or getPath(grid, row, col-1, path)) or getPath(grid, row-1, col, path):
point = row,col
path.append(point)
return True
return False
print(callGetPath(3,3)) #[(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]
print(callGetPath(2,2)) #[(0, 0), (1, 0), (1, 1)]
print(callGetPath(4,3)) #[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2)]
# Solution With Dynamic Programming
def callGetPathDp(rows, cols):
assert rows and cols > 0
grid = [[False for i in range(cols)] for j in range(rows)]
path = [];
failedPoints = set()
if(getPathDp(grid, len(grid)-1, len(grid[0])-1, path, failedPoints)):
return path
return None
def getPathDp(grid, row, col, path, failedPoints):
if( row < 0 or col < 0 or (grid[row][col] == True)):
return False
p = row, col
print(p)
if p in failedPoints:
return False
isAtOrigin = (row == 0) and (col == 0)
if(isAtOrigin or getPathDp(grid, row, col-1, path, failedPoints)) or getPathDp(grid, row-1, col, path, failedPoints):
point = row,col
path.append(point)
return True
failedPoints.add(p) #Cache results
return False
print("\n\nRunning with Dynamic Programming \n\n")
print(callGetPathDp(3,3)) #[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2), (3, 3)]
# print(callGetPathDp(4,4)) #[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (3, 2), (3, 3)]
# print(callGetPathDp(3,8)) #[(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7)] | true |
c1111f1933aeab8fa21b81df7299979e7ab2ff68 | Nishimirwe/python-algorithms | /src/interview_questions/recursionAndDynamicProgramming/easy/isPalindrome.py | 1,395 | 4.375 | 4 | # IsPalindrome --> Write a recursive function if the string passed to is a palindrome, otherwise return false
def isPalindrome(str):
strLength = len(str)
assert strLength > 0, "Length of string should be greater than 0"
# if initial length of string is one -> it definitely a palindrome
# Also handles, the last letter in an odd length palindrome
if strLength == 1:
return True
if str[0] == str[strLength - 1]:
# handles even length palindromes
if(len(str) == 2):
return True
else:
return isPalindrome(str[1: (strLength - 1)])
else:
return False
# TEST
# OddLength Palindromes
print(isPalindrome("racecar")) #ans --> True
print(isPalindrome("awesome")) #ans --> False
print(isPalindrome("level")) #ans --> True
print(isPalindrome("madam")) #ans --> True
print(isPalindrome("kayak")) #ans --> True
print(isPalindrome("tacocat")) #ans --> True
print(isPalindrome("foobar")) #ans --> False
print(isPalindrome("amanaplanacanalpanama")) #ans --> True
print(isPalindrome("amanaplanacanalpandemonium")) #ans --> False
# Even Length Palindromes
print(isPalindrome("12344321")) #ans --> True
print(isPalindrome("12345321")) #ans --> False | true |
8267427bbd6bc2c91ec94852d0f64f80e47c7d16 | Supernovacs/python | /main.py | 476 | 4.125 | 4 | def encrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
elif (char == " "):
result += " "
else:
result += chr((ord(char) + s-97) % 26 + 97)
return result
print("Enter the text you want to encode: ")
text = input()
print("Enter the key: ")
s = int(input())
print("Here's your secret message: " + encrypt(text,s)) | true |
e414ae359f0c48d04fa08f3535a62a137b7dd299 | VVivid/python-programs | /list/16.py | 217 | 4.1875 | 4 | """Write a Python program to generate and print a list of first and last 5 elements
where the values are square of numbers between 1 and 30 (both included)."""
l = [i ** 2 for i in range(1,31)]
print(l[:5],l[-5:])
| true |
cc9865ca878ab7af94ad00db8d1f6b7cf722e23a | VVivid/python-programs | /array/9.py | 297 | 4.125 | 4 | """Write a Python program to append items from a specified list."""
from array import *
array_test = array('i', [4])
num_test = [1, 2, 3, 4]
print(f"Items in the list: {num_test}")
print(f"Append items from the list: ")
array_test.fromlist(num_test)
print("Items in the array: "+str(array_test)) | true |
6d2f899345647d05fcb2666489eef6588c6df66d | VVivid/python-programs | /array/3.py | 263 | 4.34375 | 4 | """Write a Python program to reverse the order of the items in the array."""
from array import *
array_test = array('i',[1,2,3,4,5,6,7])
array_test_reverse = array_test[::-1]
print(f"Original Array: {array_test}\n"
f"Reverse Array: {array_test_reverse}")
| true |
d6cb540d3560e112018ee3372a8cc1151f5c8497 | VVivid/python-programs | /Strings/2.py | 229 | 4.21875 | 4 | """Write a Python program to count the number of characters (character frequency) in a string."""
Sample_String = 'google.com'
result = dict()
for item in Sample_String:
result[item] = Sample_String.count(item)
print(result) | true |
df5f7843f3a344c0ab4591dff759180561116413 | VVivid/python-programs | /Strings/3.py | 430 | 4.34375 | 4 | """Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
If the string length is less than 2, return instead of the empty string."""
def string_both_ends(user_input):
if len(user_input) < 2:
return 'Length smaller than 2'
return user_input[0:2] + user_input[-2:]
print(string_both_ends('w3resource'))
print(string_both_ends('w3'))
print(string_both_ends('w'))
| true |
79762246ffac80b3d8e2acb35c05a13fdc843598 | VVivid/python-programs | /array/2.py | 260 | 4.125 | 4 | """Write a Python program to append a new item to the end of the array. """
from array import *
array_test = array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Original Array {}".format(array_test))
array_test.append(10)
print('Update array :')
print(array_test)
| true |
6a24b4feda7f21aea7fcbc9e137ec929a8f02ac2 | david-weir/Programming-3-Data-Struct-Alg- | /week3/slice.py | 651 | 4.15625 | 4 | #!/usr/bin/env python3
def get_sliced_lists(lst):
final = []
no_last = lst[:-1]
no_first_or_last = lst[1:-1]
reverse = lst[::-1]
final.append(no_last)
final.append(no_first_or_last)
final.append(reverse)
return final
# def main():
# # read the list from stdin
# nums = []
# num = int(input())
# while num != -1:
# nums.append(num)
# num = int(input())
# # call the student's function with the list of numbers and ...
# lists = get_sliced_lists(nums)
# # ... print the result
# for lst in lists:
# print(lst)
# if __name__ == "__main__":
# main() | true |
0a215ca7d79e7e96bf17c5157b1b9799c7adb238 | khollbach/euler | /1_50/19/euler.py | 1,347 | 4.3125 | 4 | #!/usr/bin/python3
days_per_month = [
31, # Jan
28, # Feb
31, # Mar
30, # Apr
31, # May
30, # Jun
31, # Jul
31, # Aug
30, # Sep
31, # Oct
30, # Nov
31 # Dec
]
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
else:
return True
else:
return False
def main():
'''
Guest programmer: Eric :)
'''
count = 0
day_of_week = 1 # Day of week is 0..6 for Sunday to Saturday
day_of_month = 0 # Day of month takes values in 0..days_this_month-1
month = 0 # Months are 0..11
year = 1900
while year <= 2000:
#print('day %2d, month %2d, year %d' % (day_of_month, month, year))
if day_of_week == 0 and day_of_month == 0 and year >= 1901:
count = count + 1
# Increment day month year
day_of_week = (day_of_week + 1) % 7
days_this_month = days_per_month[month]
if month == 1 and is_leap_year(year):
days_this_month = 29 # 29
day_of_month = (day_of_month + 1) % days_this_month
if day_of_month == 0:
month = (month + 1) % 12
if month == 0:
year = year + 1
print(count)
if __name__ == '__main__':
print('l33t program b00ting up!')
main()
| false |
416ee19ddef2547d51537911b5fc40298318f4fc | alextodireanu/check_palindrome_app | /check_palindrome.py | 877 | 4.5625 | 5 | # an app that checks if a given word is a palindrome
# first method using a reversed string
def check_palindrome(word):
"""Method to validate if a word is a palindrome"""
if word == word[::-1]:
return True
else:
return False
word_to_be_checked = input('Please type the word you want to check -> ')
print(check_palindrome(word_to_be_checked))
# second method using a for loop
def check_palindrome(word):
"""Method to validate if a word is a palindrome"""
# first we find the middle of the string
middle = int(len(word)/2)
# reading the first half of the string and comparing it with the other half
for i in range(middle):
if word[i] != word[len(word)-i-1]:
return False
return True
word_to_be_checked = input('Please type the word you want to check -> ')
print(check_palindrome(word_to_be_checked))
| true |
bf5c393937be0e9fb8c5fbf17b55ef45baeb60a5 | joon628/ReadingJournal | /shapes.py | 1,706 | 4.5 | 4 | import turtle
#------------------------------------------------------------------------------
# Starter code to get things going
# (feel free to delete once you've written your own functions
#------------------------------------------------------------------------------
# Create the world, and a turtle to put in it
bob = turtle.Turtle()
# Get moving, turtle!
bob.fd(100)
# Wait for the user to close the window
turtle.mainloop()
#------------------------------------------------------------------------------
# Make some shapes
# Work through exercises 1-4 in Chapter 4.3.
#------------------------------------------------------------------------------
# NOTE: for part 2 of 4.3, you will add another parameter to this function
def square(t):
t = turtle.Turtle()
for i in range(t):
t.forward(100) #Assuming the side of a pentagon is 100 units
t.right(90)
## Polygon
def polygon(t):
#Python programming to draw pentagon in turtle programming
t = turtle.Turtle()
for i in range(t):
t.forward(100) #Assuming the side of a pentagon is 100 units
t.right(360/t)
## Circle
def circle(t):
t = turtle.Turtle()
t.circle(60)
#------------------------------------------------------------------------------
# Make some art
# Complete *at least one of* Exercise 2, 3, 4, or 5 in `shapes.py`.
#------------------------------------------------------------------------------
# If you come up with some cool drawings you'd like to share with the rest of the class, let us know!
def art(t):
t = turtle.Turtle()
for i in range(t):
t.forward(100)
t.right(3)
t.forward(20)
t.rotate(40)
t.farward(30)
| true |
17bdeb8ccdb7aca974227a921418230411756335 | RobertNeuzil/leetcode | /fatherson.py | 497 | 4.125 | 4 | """
Use a recursion function to find out when the father will be twice as old as his son
"""
def father_son(fatherAge, sonAge):
while sonAge < 1000:
if fatherAge / 2 == sonAge:
print (f"The father will be twice as old as the son when the son is {sonAge} and the father is {fatherAge}")
return True
else:
return father_son(fatherAge + 1, sonAge + 1)
print (f"those parameter can not be met")
return False
father_son(62, 23) | true |
082f48d4ab9ce8e939954ca0eeb3244e7f08344c | stanmark2088/FizzBuzz | /fizzbuzz/fizbuzz.py | 516 | 4.25 | 4 | """
Write a program that prints the numbers from 1 to 100. But:
- for multiples of three print “Fizz” instead of the number and
- for the multiples of five print “Buzz”.
- For numbers which are multiples of both three and five print “FizzBuzz”.
"""
def fizzbuzz():
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print ("FizzBuzz")
elif i % 3 == 0:
print ("Fizz")
elif i % 5 == 0:
print ("Buzz")
else:
print(i) | true |
78ff2fa79302a923062788129b316090657da57d | sudhamshu4testing/PracticePython | /Program_to_count_vowels.py | 316 | 4.15625 | 4 | #Program to count the vowels in a given sentence/word
#Vowels
v = 'aeiou'
statement = 'Sudhamshu'
#Take input from the user
#statement = input("Enter a sentence or word: ")
statement = statement.casefold()
count = {}.fromkeys(vowels,0)
for char in statement:
if char in count:
count[char] += 1
print(count) | true |
51b1a59808f936b2dbbdcfcaab3dd5fa18b06348 | sudhamshu4testing/PracticePython | /ConverToListAndTuple.py | 447 | 4.4375 | 4 | #Program to convert the user entered values to List and Tuple
#Ask user to provide a sequence of comma seperated numbers
numbers = input("Proved the sequence of comma seperated numbers: ")
l = list(numbers)
#list can also be written as follow
#l = numbers.split(",")
t = tuple(numbers)
print("The sequence of the numbers you provided are converted to list as: ",l)
print("The sequence of the numbers you provided are converted to tuple as: ",t) | true |
c320948b0612cf1459bbcaae34aa045c6a03d084 | sudhamshu4testing/PracticePython | /Rock_Scissor_Paper_Game.py | 1,434 | 4.4375 | 4 | #Program for a game to play between 2 users and decide who wins the "Rock, Scissor and Paper" game
#Importing "sys" module to use "exit"
import sys
#Let's say if user1 selects "Rock" and user2 selects "Scissor", user1 will win because "Scissor" can't break the rock
#Similar way if user1 selects "Paper" and user2 selects "Scissor", user2 will will because "Scissor" can cut paper
#Let's ask users to provide their names
first_user_name = raw_input("What's your name? ")
second_user_name = raw_input("And what is your's? ")
#Let's ask users to provide their answers to decide who wins
first_user_answer = raw_input("%s, Do you want to choose Rock, Scissor or Paper? " %first_user_name)
second_user_answer= raw_input("%s, Do you want to choose Rock, Scissor or Paper? " %second_user_name)
#Writing a function to compare and decide who wins
def compare(user1,user2):
# If both the users choosed the same option
if user1 == user2:
return("It is a tie!")
elif user1 == 'Rock':
if user2 == 'Scissor':
return("Rock wins!")
else:
return("Paper wins!")
elif user1 == 'Scissor':
if user2 == 'Paper':
return("Scissor wins!")
else:
return("Rock wins!")
elif user1 == 'Paper':
if user2 == 'Rock':
return("Rock wins!")
else:
return("Scissor wins!")
else:
return("Invalid input. You have not choose any of the options above mentioned")
sys.exit()
print(compare(first_user_answer,second_user_answer))
| true |
4c8756c4a16ee1fa314cf15aff1527902709cbf7 | sudhamshu4testing/PracticePython | /Email_Extraction.py | 209 | 4.125 | 4 | #Program to understand the regular expressions in detail
import re
pattern = r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)"
str = "Please contact test@email.com"
match = re.search(pattern,str)
if match:
print(match.group()) | true |
6043f021003d5daf6a77c89e5d5d1b5493465b96 | abhimanyupandey10/python | /even_function_sum.py | 345 | 4.1875 | 4 | # This program finds sum of even numbers of array using function
def findSumOfEvenNmbers (numbers):
sum = 0
for x in numbers:
if x % 2 == 0:
sum = sum + x
return sum
####################### Main code starts #####################
numbers = [6,7,8,9,1,2,3,4,5,6]
sum = findSumOfEvenNmbers (numbers)
print (sum) | true |
8a3c0e55429879985ff9683e22aba23055148f9f | AmreshTripathy/Python | /59_recursion_factorial.py | 442 | 4.1875 | 4 | # n = int(input('Enter a number: '))
# product = 1
# for i in range(1, n+1):
# product = product * i
# print (product)
# def factorial_iter(n):
# product = 1
# for i in range(1, n+1):
# product = product * i
# return product
def factorial_recurse(n):
if ( n == 1 or n == 0):
return 1
return n * factorial_recurse(n-1)
n = int(input('Enter a Number: '))
print (factorial_recurse(n)) | false |
9ae92c18a01a8ac79334573b3488606ccd9889a9 | AmreshTripathy/Python | /35_pr6_05.py | 226 | 4.1875 | 4 | names = ['harry', 'subham', 'rohit', 'Aditi', 'sipra']
name = input('Enter the name to check:\n')
if (name in names):
print ('Your name is present in the list')
else:
print ('Your name is not present in the list') | true |
6669679241d42a449d45ceb9c3a1601bd29e0e0a | ConradMare890317/Python_Crash.course | /Chap07/even_or_odd.py | 349 | 4.25 | 4 | prompt = "Enter a number, and I'll tell you if it's even or odd: "
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
number = input(prompt)
if number == 'quit':
active = False
elif int(number) % 2 == 0:
print(f"\nThe number {number} is even.")
elif int(number) % 2 != 0:
print(f"\nThe number {number} is odd.")
| true |
caf7c299c5edfb43bd8a7e4d2d01506a72c62494 | samarthgowda96/oop | /interface.py | 911 | 4.375 | 4 | # Python Object Oriented Programming by Joe Marini course example
# Using Abstract Base Classes to enforce class constraints
from abc import ABC,abstractmethod
class JSONify(ABC):
@abstractmethod
def toJSON(Self):
pass
class GraphicShape(ABC):
def __init__(self):
super().__init__()
@abstractmethod #override method in the child classes
def calcArea(self):
pass
class Circle(GraphicShape,JSONify):
def __init__(self, radius):
self.radius = radius
def calcArea(self):
return 3.14 *(self.radius**2)
def toJSON(self):
return f"{{\"circle\": {str(self.calcArea())}}}"
class Square(GraphicShape):
def __init__(self, side):
self.side = side
def calcArea(self):
return self.side*self.side
#g = GraphicShape()
c = Circle(10)
print(c.calcArea())
#s = Square(12)
#print(s.calcArea())
print(c.toJSON())
| true |
50e430e625a115ba20ab470dc0e5c36e9cf4ee8d | kerrymcgowan/AFS_505_u1_spring_2021 | /assignment2/ex6_studydrill1.py | 829 | 4.34375 | 4 | # Make a variable
types_of_people = 10
# Make a variable with an fstring
x = f"There are {types_of_people} types of people."
# Make a variable
binary = "binary"
# Make a variable
do_not = "don't"
# Make a variable with an fstring
y = f"Those who know {binary} and those who {do_not}."
# Print a variable
print(x)
# Print a variable
print(y)
# Print an fstring
print(f"I said: {x}")
# Print an fstring
print(f"I also said: '{y}'")
# Make a variable
hilarious = False
# Make a variable with a blank variable at the end
joke_evaluation = "Isn't that joke so funny?! {}"
# Print a variable within a variable using .format syntax
print(joke_evaluation.format(hilarious))
# Make a string
w = "This is the left side of..."
# Make a string
e = "a string with a right side."
# Print 2 strings by adding them together
print(w + e)
| true |
8e2d9c92757f8db4b93c3be98d28a5fd5311f6a8 | trodfjell/PythonTeachers2021 | /Matematikk/Pytagoras.py | 986 | 4.1875 | 4 | # Dette programmet kan brukes for å finne lengden på en ukent side av en rettvinklet trekant
# Programmet ber først brukeren å fortelle om det er hypotenusen eller et av katetenes lengde som er ukjent
# Så ber den om lengden på begge katetene eller hypotenusen og kateten
# Så regner den seg frem til lengden av den ukjente siden
import math
print('Hvilken side av den rettvinklede trekanten er ukjent? (hypotenus/katet)')
ukjent = input()
if (ukjent.lower() == 'hypotenus'):
a = float(input('Hva er lengden av første katet? '))
b = float(input('Hva er lengden av andre katet? '))
c = math.sqrt(a ** 2 + b ** 2)
print('Lengden av hypotenus er ' + str(c))
elif (ukjent.lower() == 'katet'):
c = float(input('Hva er lengden av hypotenusen? '))
a = float(input('Hva er lengden av en av katetene? '))
b = math.sqrt(c ** 2 - a ** 2)
print('Lengden av den ukjente kateten er ' + str(b))
else:
print('Du må skrive enten hypotenus eller katet') | false |
0761ca27262a5e66f956eddf201448f3a5f35cc1 | BMorgenstern/MergeSort | /MergeSort/mtest.py | 1,034 | 4.28125 | 4 | from mergesort import *
import sys
def getIntArray():
retlist = []
while True:
num = input("Enter an integer value to add to the array, or hit Enter to stop inputting values ")
if num == "":
return retlist
try:
retlist.append(int(num,10))
except ValueError:
print(num+" is not a number")
def main(args):
Merged = []
#hardcoded array given as an example
#list1 = [123, 34, 189, 56, 150, 12, 9, 240]
list1 = getIntArray()
print("Before sorting: ")
print(list1)
if len(args) < 2:
Merged = MergeSort(list1)
else:
'''
Number of splits can be given from the terminal,
2 is assumed when the input is invalid of no input is given
'''
try:
splits = int(args[1])
except ValueError:
print(args[1]+' is not a number; assuming 2...')
splits = 2
debug = len(args) > 2
'''
print debug info if there any terminal arguments beyond the number of splits
'''
Merged = MergeSort(list1, splits, debug)
print("After sorting : ")
print(Merged)
if __name__ == '__main__':
main(sys.argv) | true |
e768ac54492abadfc2a859e1272e8d0747560507 | aniketrathore/py-dsa | /stacks/stack.py | 1,131 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.prev = None
class Stack:
def __init__(self):
self.head = None
self.size = 0
def push(self, value):
if self.head:
new_node = Node(value=value)
new_node.prev = self.head
self.head = new_node
else:
self.head = Node(value=value)
self.size += 1
print("Value Pushed.")
def pop(self):
if self.head:
prev_node = self.head.prev
self.head = prev_node
self.size -= 1
print("Value Popped")
else:
print("Stack Is Empty.")
def top(self):
if self.head:
print(self.head.value)
else:
print("Stack Is Empty.")
def get_size(self):
print(self.size)
def is_empty(self):
print(False if self.head else True)
def display(self):
iterator = self.head
while iterator:
print(iterator.value)
iterator = iterator.prev
def get_max(self):
"""To be implemented"""
| false |
9fa47ad84849bdc739cff0462629cd2b1a31e594 | adriandrag18/Tema1_ASC | /tema/consumer.py | 1,679 | 4.21875 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread, current_thread
from time import sleep
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
Constructor.
:type carts: List
:param carts: a list of add and remove operations
:type marketplace: Marketplace
:param marketplace: a reference to the marketplace
:type retry_wait_time: Time
:param retry_wait_time: the number of seconds that a producer must wait
until the Marketplace becomes available
:type kwargs:
:param kwargs: other arguments that are passed to the Thread's __init__()
"""
super().__init__(**kwargs)
self.carts = carts
self.marketplace = marketplace
self.retry_wait_time = retry_wait_time
def run(self):
for cart in self.carts:
cart_id = self.marketplace.new_cart()
for operation in cart:
for _ in range(operation['quantity']):
if operation['type'] == 'add':
while not self.marketplace.add_to_cart(cart_id, operation['product']):
sleep(self.retry_wait_time)
elif operation['type'] == 'remove':
self.marketplace.remove_from_cart(cart_id, operation['product'])
products = self.marketplace.place_order(cart_id)
for product in products:
print(f"{current_thread().name} bought {product}")
| true |
83c85f73f8dfac3b5d543f189e2f6939bf47dfc1 | nadia1038/Assignment-4 | /OneFour.py | 485 | 4.4375 | 4 | #1. Write a Python program to calculate the length of a string
String = "abcdefghijklmnopqrstuvwxyz"
print(len(String))
#4. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
#Sample String: 'restart'
#Expected Result: 'resta$t'
string="restart"
array=[]
new_string=""
for i in string:
array.append(i)
array[5]='$'
for i in array:
new_string +=i
print(new_string)
| true |
607d16b743dddf662f6a306422e65b936277e375 | milenaS92/HW070172 | /L04/python/chap3/exercise02.py | 472 | 4.28125 | 4 | # this program calculates the cost per square inch
# of a circular pizza
import math
def main():
print("This program calculates the cost per square inch of a circular pizza")
diam = float(input("Enter the diameter of the pizza in inches: "))
price = float(input("Enter the price of a pizza: "))
radius = diam / 2
surface = math.pi * (radius**2)
costPerInch = price / surface
print("The cost per square inch is: ", round(costPerInch,2))
main()
| true |
9b692103e23ee713b3c9e166c9832cad321c9f54 | milenaS92/HW070172 | /L04/python/chap3/exercise11.py | 318 | 4.25 | 4 | # This program calculates the sum of the first n natural numbers
def main():
print("This program calculates the sum of the first n natural numbers")
n = int(input("Please enter the natual number: "))
sum = 0
for i in range(0,n+1):
sum += i
print("The sum of the numbers is: ", sum)
main()
| true |
925177ca3178674f1b11986f0fd85ba0c2edac1a | milenaS92/HW070172 | /L05/python/chap7/excercise05.py | 459 | 4.125 | 4 | # exercise 5 chap 7
def bmiCalc(weight, height):
bmi = weight * 720 / (height**2)
if bmi < 19:
return "below the healthy range"
elif bmi < 26:
return "within the healthy range"
else:
return "above the healthy range"
def main():
weight = float(input("Please enter your weight in pounds: "))
height = float(input("Please enter your height in inches: "))
print("Your BMI is", bmiCalc(weight, height))
main()
| true |
7a30a96b59ea58675216e5f9d00d2b4e243303e8 | kjempire9/python-beginner-codes | /factorial.py | 354 | 4.4375 | 4 |
# The following codes takes in a number and returns its factorial.
# For example 5! = 120.
def factorial(a):
try:
if int(a) == 1:
return 1
else:
return int(a)*factorial(int(a)-1)
except ValueError:
print("You did not enter an integer!!")
x = input("Enter an integer : ")
print(factorial(x))
| true |
0e861f7d9e7fb8da98ddbc0cdd1256bf5e0ff958 | feeka/python | /[4]-if else try-catch.py | 447 | 4.15625 | 4 | # -*- coding: utf-8 -*-
x=int(input("Enter 1st number: "))
y=int(input("Enter 2nd number: "))
#line indenting plays great role in this case!
if x>y:
print(str(x)+" is GREATER than "+str(y))
elif x<y:
print(str(x)+" is LESS than "+str(y))
else:
print(str(x)+" is EQUAL to "+str(y))
#try-catch
a=input("Enter number: ")
try:
g=int(a)
print(g)
except:
print("Oops entered is not a number")
| true |
6cc15739329b791ad5f36f630fd163814e946e24 | ppmx/cryptolib | /tools/hamming.py | 1,394 | 4.375 | 4 | #!/usr/bin/env python3
""" Package to compute the hamming distance.
The hamming distance between two strings of equal length is the number of
of positions at which the corresponding symbols are different.
"""
import argparse
import unittest
def hamming(string_a, string_b):
""" This function returns the hamming distance as the number of different
bits for the given two byte arrays.
"""
return sum([bin(a ^ b).count('1') for a, b in zip(string_a, string_b)])
class TestHamming(unittest.TestCase):
""" Some unittests for this package. """
def test_hamming(self):
""" Tests the hamming function. """
string_a, string_b = b'this is a test', b'wokka wokka!!!'
self.assertEqual(hamming(string_a, string_b), 37)
def cli():
""" Provides a command line interface. Pass -h as argument to get some information.
Example:
$ ./hamming.py "crypto is fun" "beer is tasty"
The hamming distance is: 34
"""
parser = argparse.ArgumentParser(
description='Tool to compute the hamming distance of both passed strings.'
)
parser.add_argument('string_a', type=lambda c: c.encode())
parser.add_argument('string_b', type=lambda c: c.encode())
args = parser.parse_args()
result = hamming(args.string_a, args.string_b)
print("The hamming distance is:", result)
if __name__ == "__main__":
cli()
| true |
44e69f64edbe5493a73bc28b79ed4c14262163c5 | melissafear/CodingNomads_Labs_Onsite | /week_01/04_strings/05_mixcase.py | 682 | 4.625 | 5 | '''
Write a script that takes a user inputted string
and prints it out in the following three formats.
- All letters capitalized.
- All letters lower case.
- All vowels lower case and all consonants upper case.
'''
text = "here is a string of text"
print(text.upper())
print(text.lower())
# OPTION ONE
upper = text.upper()
print(upper.replace("A","a").replace("E","e").replace("I","i").replace("O","o").replace("U","u"))
# OPTION TWO
vowels = ["a", "e", "i", "o", "u"]
for letter in text:
if letter in vowels:
text = text.replace(letter,letter.lower())
if letter not in vowels:
text = text.replace(letter,letter.upper())
print(text)
| true |
4dffd43a38bb6413563021c5d20009090238120b | melissafear/CodingNomads_Labs_Onsite | /week_02/06_tuples/01_make_tuples.py | 615 | 4.34375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sorted_list = sorted(my_list)
#if list is an uneven number append a 0
length = len(sorted_list)
if length % 2 == 1:
sorted_list.append(0)
length = len(sorted_list)
new_list = []
for i in range(0,length,2 ):
newtuple = sorted_list[i], sorted_list[i+1]
new_list.append(newtuple)
print(new_list)
| true |
158c564cc85e5e7ebb9c6943f67f1672c1ea0d4f | melissafear/CodingNomads_Labs_Onsite | /week_02/08_dictionaries/09_01_duplicates.py | 483 | 4.1875 | 4 | '''
Using a dictionary, write a function called has_duplicates that takes
a list and returns True if there is any element that appears more than
once.
'''
# count the occurrences of each item and store them in ther dictionary
def has_duplicates(list_):
my_dict = {}
for item in my_list:
if item in my_dict:
my_dict[item] += 1
return True
else:
my_dict[item] = 1
my_list = [1, 2, 3, 3]
print(has_duplicates(my_list))
| true |
09c9533f5c28e11aff42f91813f61e4fae6891f4 | melissafear/CodingNomads_Labs_Onsite | /week_03/02_exception_handling/04_validate.py | 537 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
isinteger = "nope"
while isinteger == "nope":
user_input = input("pls type a number: ")
try:
int(user_input)
except ValueError as ve:
print("That was not an integer, try again: ")
else:
print("its an integer!")
isinteger = "yes"
| true |
bd8e455a8c043737ed67f8db322bea469758e3ac | melissafear/CodingNomads_Labs_Onsite | /week_02/07_conditionals_loops/Exercise_02.py | 799 | 4.3125 | 4 | '''
Take in a number from the user and print "Monday", "Tuesday", ...
"Sunday", or "Other" if the number from the user is 1, 2,... 7,
or other respectively. Use a "nested-if" statement.
'''
days_of_week = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun", "That's not a day of the week!"]
user_input = int(input("pls enter a number and I will tell you the day of the week: "))
print(days_of_week[user_input-1])
# OR
if user_input == 1:
print("Monday")
elif user_input == 2:
print("Tuesday")
elif user_input == 3:
print("Wednesday")
elif user_input == 4:
print("Thursday")
elif user_input == 5:
print("Friday")
elif user_input == 6:
print("Saturday")
elif user_input == 7:
print("Sunday")
elif user_input >= 8:
print("That's not a weekday, try again")
| true |
b9ade628410db43de3d0448901ff69ecd70762c3 | treetrunkz/CalorieTracker | /caltrack.py | 1,648 | 4.3125 | 4 |
# this function uses sum and len to
# return the sum of the numbers=
def list_average(nums_list):
return sum(nums_list) + len(nums_list)
print('\n Welcome to the calorie goals calculator! \n \n We will be going through your diet and calculating and comparing your calorie goals and your caloric intake. \n')
goals = int(input('Now then, What are your daily caloric goals? '))
x = int(input('How many meals do we want to calculate calories for? '))
activity = 0
# create the empty list called nums
nums = []
#prompt 4 times for format
print('You will be prompted for the caloric data for each meal.')
for n in range(x):
#make range(x) x an input variable for how many meals
n = float(input('Enter the number of calories for each of your meals: '))
#n will be the amount of calories for each meal.
nums.append(n)
#will append each amount for each meal in the list.
#call list_average
#change call average or sum or anything math with this.
avg = list_average(nums)
print('The calories we are tracking for each day of your diet are:')
print(avg - x)
activity = int(input("What is your activty level, 1. Not Active, 2. Lightly Active 3. Active or 4. Very Active: "))
while activity == 1:
act = (avg - 200)
if activity == 2:
act = (avg - 400)
if activity == 3:
act = (avg - 600)
if activity == 4:
act = (avg - 800)
print('After your caloric intake has been calculated with your activity, your calories are')
print(act - x, 'calories.')
print('You are currently')
goals2=((act - x) - goals)
if goals2 > 0:
print('over your caloric goals by: ')
if goals2 < 0:
print('under your calorie goals by: ')
print(goals2)
| true |
2e58bc18c81abfb4563c2c74d99bcc131255e304 | anmol-sinha-coder/LetsUpgrade-AI_ML | /Week-1/Assignment-1.py | 2,186 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # <font color="blue">Question 1: </font>
# ## <font color="sky blue">Write a program to subtract two complex numbers in Python.</font>
# In[1]:
img1=complex(input("Enter 1st complex number: "))
img2=complex(input("Enter 2nd complex number: "))
print("\nSubtracting 2nd complex number from 1st complex number, we get",img1-img2)
# # <font color="green">Question 2: </font>
# ## <font color="chartreuse">Write a program to find the fourth root of a number.</font>
# In[2]:
num=float(input("Enter a real number: "))
print("\nFourth(4th) root of the number is",num**(1/4))
# # <font color="maroon">Question 3: </font>
# ## <font color="red">Write a program to swap two numbers in Python with the help of a temporary variable.</font>
# In[3]:
a=int(input("Enter value of 'a': "))
b=int(input("Enter value of 'b': "))
print("\nValue of a={}\t|\tValue of b={}".format(a,b))
t=a
a=b
b=t
print("\nAfter swap,\nValue of a={}\t|\tValue of b={}".format(a,b))
# # <font color="indigo">Question 4: </font>
# ## <font color="violet">Write a program to swap two numbers in Python without using a temporary variable.</font>
# In[4]:
a=int(input("Enter value of 'a': "))
b=int(input("Enter value of 'b': "))
print("\nValue of a={}\t|\tValue of b={}".format(a,b))
a=a+b
b=a-b
a=a-b
print("\nAfter swap,\nValue of a={}\t|\tValue of b={}".format(a,b))
# # <font color="Brown">Question 5: </font>
# ## <font color="Orange">Write a program to convert Fahrenheit to kelvin and celsius both.</font>
# In[5]:
fahr=float(input("Enter temperature in degrees Fahrenheit: "))
cels= 5/9*(fahr-32)
kelvin=cels+273.15
print("\nThe temperature in Kelvin is",round(kelvin,2))
print("The temperature in Celsius is",cels)
# # <font color="pink">Question 6: </font>
# ## <font color="gold">Write a program to demonstrate all the available data types in Python.</font>
# In[6]:
i=4
f=4.5
c=4+5j
b=True
word="Hello world"
l=[4,'five',6.7]
t=(4,"five",6.7)
s={4,'five',6.7}
d={"One":1, 2:'Two', 'Three':3}
print("\n\tDATA TYPES\nNumeric: ",type(i),type(f),type(c),"\nBoolean: ",type(b),"\nSequential:",type(word),type(l),type(t),"\nOther:",type(d),type(s),)
| true |
35801887a4e6628db3c7175e0aa7360949426435 | vivekdevaraju/Coding-Challenges | /letterCount.py | 936 | 4.1875 | 4 | '''
Have the function LetterCountI(str) take the str parameter being passed
and return the first word with the greatest number of repeated letters. For
example: "Today, is the greatest day ever!" should return 'greatest' because
it has 2 e's (and 2 t's) and it comes before 'ever' which also has 2 e's. If
there are no words with repeating letters return -1. Words will be separated
by spaces.
Example:
Input: "Hello apple pie"
Output: Hello
Input: "No words"
Output: -1
'''
def LetterCountI(strParam):
str_arr = strParam.split()
count = 0
greatest_length = '-1'
for i in range(len(str_arr)):
for j in range(len(str_arr[i])):
new_count = 0
for k in range(j+1, len(str_arr[i])):
if str_arr[i][j] == str_arr[i][k]:
new_count+=1
if new_count > count:
count = new_count
greatest_length = str_arr[i]
return greatest_length
print(LetterCountI("Hello apple pie")) | true |
97ef4e5aa4ebc325bf26ad70cba98fc179671456 | randyarbolaez/pig-latin | /src/main.py | 1,262 | 4.40625 | 4 | VOWELS = ['a','e','i','o','u']
def remove_punctuation(string):
correct_string = ''
for letter in string:
if letter.isalpha():
correct_string += letter
return correct_string
def input_string_to_translate_to_pig_latin(prompt):
return input(prompt).strip().lower()
def split_str(input_str):
return input_str.split()
def word_does_not_begin_with_vowel(word):
pig_latin_word = word
for letter in word:
if letter not in VOWELS:
pig_latin_word = pig_latin_word.replace(letter,'')
pig_latin_word += letter
if letter in VOWELS:
return pig_latin_word + 'ay '
def translate_to_pig_latin(words):
pig_latin_str = ''
correct = remove_punctuation(words)
for word in words:
if word[0] in VOWELS:
word_with_way = word + 'yay '
pig_latin_str += word_with_way
continue
else:
pig_latin_str += word_does_not_begin_with_vowel(word)
return pig_latin_str
def main():
user_input = input_string_to_translate_to_pig_latin('What would you like to translate to pig latin? ')
list_of_words = split_str(user_input)
pig_latin = translate_to_pig_latin(list_of_words)
print(pig_latin)
main()
| false |
50b7cecd46498a3bc6bc7cc5383f2152b3f3b2ba | christian-miljkovic/interview | /Leetcode/Algorithms/Medium/Arrays/CampusBikes.py | 2,282 | 4.3125 | 4 | """
On a campus represented as a 2D grid, there are N workers and M bikes, with N <= M. Each worker and bike is a 2D coordinate on this grid.
Our goal is to assign a bike to each worker. Among the available bikes and workers, we choose the (worker, bike) pair with the shortest Manhattan distance between each other, and assign the bike to that worker. (If there are multiple (worker, bike) pairs with the same shortest Manhattan distance, we choose the pair with the smallest worker index; if there are multiple ways to do that, we choose the pair with the smallest bike index). We repeat this process until there are no available workers.
The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.
Return a vector ans of length N, where ans[i] is the index (0-indexed) of the bike that the i-th worker is assigned to.
Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: [1,0]
Explanation:
Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is [1, 0].
"""
# Time Complexity: O(n*m) where n is the len of workers and m is the len of bikes
# Space Complexity: O(n*m)
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]:
if not workers:
return []
bike_taken_set = set()
return_list = [-1] * len(workers)
dist_list = []
for i, worker in enumerate(workers):
for j, bike in enumerate(bikes):
dist_list.append((manhattan_distance(worker,bike),i,j))
count = 0
worker_len = len(workers)
sorted_list = sorted(dist_list, key=lambda x: (x[0],x[1],x[2]))
for element in sorted_list:
if count == worker_len:
break
dist, worker_index, bike_index = element
if return_list[worker_index] == -1 and bike_index not in bike_taken_set:
return_list[worker_index] = bike_index
bike_taken_set.add(bike_index)
count += 1
return return_list
def manhattan_distance(worker,bike):
return abs(worker[0] - bike[0]) + abs(worker[1] - bike[1])
| true |
643ebd3619eef099d5bc905e5d05944720fe4f5f | christian-miljkovic/interview | /Leetcode/Algorithms/Easy/Trie/LongestWordInDict.py | 2,397 | 4.125 | 4 | """
Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, return the empty string.
Example 1:
Input:
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input:
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Note:
All the strings in the input will only contain lowercase letters.
The length of words will be in the range [1, 1000].
The length of words[i] will be in the range [1, 30].
"""
class Trie(object):
def __init__(self):
self.trie = dict()
self.end = False
def add_word(self, word):
temp = self
for char in word:
if char not in temp.trie:
temp.trie[char] = Trie()
temp = temp.trie[char]
temp.end = True
def find_longest_word(self, word):
temp = self
word_len = 0
for char in word:
if char not in temp.trie or not temp.trie[char].end:
break
word_len += 1
temp = temp.trie[char]
return word_len
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
longest_words = []
longest_length = 0
for word in words:
trie.add_word(word)
for word in words:
word_len = trie.find_longest_word(word)
if word_len > longest_length:
longest_words = []
longest_words.append(word)
longest_length = word_len
elif word_len == longest_length:
longest_words.append(word)
return sorted(longest_words)[0]
| true |
c97cda747343a105c055e5f66bcbc6230d193aff | christian-miljkovic/interview | /Algorithms/TopologicalSort.py | 1,182 | 4.25 | 4 | # Topological sort using Tarjan's Algorithm
from DepthFirstSearch import AdjacencyList
def topologicalSort(graph, vertexNumber, isVisited, stack):
"""
@graph: an adjacency list representing the current
@vertex: vertex where we want to start the topological sort from
@isVisited: list that determines if the vertex has already been visited
@stack: list that represents a stack where we will place a vertex once it is processed
"""
if(vertexNumber in isVisited):
return
# pre-process the vertex
isVisited.append(vertexNumber)
# Check for when we have a leaf with no outgoing edges
if(vertexNumber not in graph.keys()):
return
# graph represents an adjacency list (implemented with dict in python) where the vertex number is the key
# to the list of children
for child in graph[vertexNumber]:
topologicalSort(graph,child,isVisited,stack)
stack.append(vertexNumber)
return stack
if __name__ == '__main__':
adjList = AdjacencyList()
adjList.addNode(0,1,2)
adjList.addNode(1,2)
adjList.addNode(2,0,3)
adjList.addNode(3,3)
print(topologicalSort(adjList.graph,0,[],[]))
| true |
15cd88ccd33ef96a95b333f5bae7db1037c8b674 | christian-miljkovic/interview | /CrackingCodingInterview/ArraysStrings/Urlify.py | 571 | 4.375 | 4 | """
Chapter 1 Array's and Strings URLify problem
Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string.
"""
def urlIfy(strToUrl):
str_list = strToUrl.split()
ret_str = ""
for i in range(0, len(str_list) - 1):
ret_str += str_list[i] + "%20"
ret_str += str_list[len(str_list) - 1]
return ret_str
if __name__ == "__main__":
str_input = "Mr John Smith "
print(urlIfy(str_input)) | true |
d148820c8eed0b6bc590f5e6f4816a3285cef81f | christian-miljkovic/interview | /CrackingCodingInterview/DynamicProgramming/RecursiveMultiply.py | 286 | 4.21875 | 4 | # Chapter 8
# Recursive Multiply
# Time Complexity: O(b)
def multiply(a, b):
if a == 0 or b == 0:
return 0
elif b == 1:
return a
else:
b -= 1
a += multiply(a, b)
return a
if __name__ == "__main__":
print(multiply(4,2))
| false |
68198a14cc31ac3625adc8b9bdf7946f051304b9 | christian-miljkovic/interview | /Leetcode/Algorithms/Easy/DynamicProgramming/ClimbingStairs.py | 1,406 | 4.125 | 4 | """
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""
# Tabulation
# Time Complexity: O(n)
# Time Complexity: O(1)
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
prev = 0
curr = 1
for i in range(n):
tmp = prev + curr
prev = curr
curr = tmp
return curr
# Memoization
class Solution:
def climbRec(self, n: int, look_up: list) -> int:
if n <= 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
elif n in look_up:
return look_up[n]
else:
look_up[n] = self.climbRec(n-1,look_up) + self.climbRec(n-2,look_up)
return look_up[n]
def climbStairs(self, n: int) -> int:
look_up = dict()
return self.climbRec(n, look_up) | true |
8abe091f2738279cee6ca403284c1217dcea9e2c | christian-miljkovic/interview | /CrackingCodingInterview/DynamicProgramming/RobotGrid.py | 931 | 4.3125 | 4 | """
Chapter 8 Dynamic Programming and Recursion
Problem - Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can move in two direction, right and down, but certain cells are "off limits" such that
the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.
"""
def getPath(matrix, i, j, path):
if i < 0 or j < 0:
return
elif matrix[i][j] == '*':
return
elif i == 0 and j == 0:
path.append((i,j))
return path
else:
pathOne = getPath(matrix, i - 1, j, path.append((i-1,j)))
pathTwo = getPath(matrix, i, j - 1, path.append((i,j-1)))
return min(len(pathOne), len(pathTwo))
matrix = [["","","","",'*'],
['*',"","",'*',""],
["",'*',"","",""]
]
path = []
print(getPath(matrix, len(matrix)-1, len(matrix[0])-1,path)) | true |
6711996b47819cb7d35bca835c41e2f80637b5e6 | christian-miljkovic/interview | /CrackingCodingInterview/ArraysStrings/RotateMatrix.py | 802 | 4.21875 | 4 | """
Chapter 1
Problem - Rotate Matrix: Rotate a Matrix 90 degrees
"""
def rotateMatrix(matrix):
size = len(matrix)
for layer in range(size//2):
first = layer
last = size - layer - 1
for i in range(first, last):
top = matrix[layer][i]
# left to top
matrix[layer][i] = matrix[-i - 1][layer]
# bottom to left
matrix[-i - 1][layer] = matrix[-layer - 1][-i - 1]
# right to bottom
matrix[-layer - 1][-i - 1] = matrix[i][-layer - 1]
# top to right
matrix[i][-layer - 1] = top
return matrix
if __name__== "__main__":
testArray = [
[1,2,3],
[4,5,6],
[7,8,9],
]
print(rotateMatrix(testArray))
| true |
2981f3195c66cdf86858edea161cd51ef561650a | Neogarsky/phyton | /main1.py | 450 | 4.34375 | 4 | ''' 1-ая задача Выяснить тип результата выражений:
doc = 15 * 3
15 / 3
15 // 2
15 ** 2 '''
print(type(15 * 3))
print(type(15 / 3))
print(type(15 // 2))
print(type(15 ** 2))
#первый вариант
print(f'type 15 * 3 {type(15 * 3)},'
f'type 15 / 3 {type(15 / 3)},'
f'type 15 // 2 {type(15 // 2)},'
f'type 15 ** 2 {type(15 ** 2)}')
#второй вариант
| false |
de80743e4c1e82678c0c543317bf6d5fa09f6ff9 | cooltreedan/NetworkProgrammability | /tried/json-example.py | 783 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding=utf-8 -*-
# Python contains very useful tools for working with JSON, and they're
# part of the standard library, meaning they're built into Python itself.
import json
# We can load our JSON file into a variable called "data"
with open("json-example.json") as f:
data = f.read()
# json_dict is a dictionary, and json.loads takes care of
# placing our JSON data into it.
json_dict = json.loads(data)
# Printing information about the resulting Python data structure
print("The JSON document is loaded as type {0}\n".format(type(json_dict)))
print("Now printing each item in this document and the type it contains")
for k, v in json_dict.items():
print(
"-- The key {0} contains a {1} value.".format(str(k), str(type(v)))
)
| true |
d648148ab5acd683aacf3b8cef81dbd0c53a0213 | joeysal/astr-119-hw-2 | /dictionary.py | 467 | 4.375 | 4 | #define a dictionary data structure
#dictionaries have key:valyue pairs for the elements
example_dict = {
"class" : "ASTR 119",
"prof" : "Brant",
"awesomeness" : 10
}
print ("The type of example_dict is ", type(example_dict))
#get value via key
course = example_dict["class"]
print(course)
example_dict["awesomeness"] += 1
#print the dictionary
print(example_dict)
#print dictionary element by element
for x in example_dict.key():
print(x, example_dict[x]) | true |
d010f9ac5a0e794325476ad3f6b7e7d17e8e6706 | Tahaa2t/Py-basics | /Conditions.py | 1,231 | 4.34375 | 4 | #-----------------------------simple if else ------------------------------------
#BMI calculator
height = float(input("Enter height in cm: "))
weight = float(input("Enter weight in kg: "))
height = height/100
bmi = round(weight/(height**2)) #round = round off to nearest whole number
if bmi < 18.5:
print(f"{bmi}: Underweight")
elif bmi < 25: #else if() <---cpp = elif <---Python
print(f"{bmi}: Normal weight")
elif bmi < 30:
print(f"{bmi}: overweight")
elif bmi < 35:
print(f"{bmi}: obese")
elif bmi >= 35:
print(f"{bmi}: overweight")
else:
print("Enter correct weight")
#------------------------------Nested if else---------------------------------------
#Roller coaster ride,
# if heignt >= 120cm and age >= 10, charge 10$
# if heignt >= 120cm and age < 10, charge 7$
# if height < 120cm, not allowed
print("Welcome to rollercoaster")
height = int(input("Enter height in cm: "))
age = int(input("Enter age: "))
if height >= 120: #>=, <=, >, <, ==, !=
if age >= 10:
print("You're good to go, 10$")
elif age <10:
print("You're good to go, 7$")
else:
print("nope...!")
#for multiple conditions, use 'and'/'or'
# eg: if age < 10 and age >= 5: ... | false |
1dd908f565bfacec361dcfec080dac61c86146ca | Tahaa2t/Py-basics | /filing.py | 1,020 | 4.5625 | 5 |
#-----------------Reading from file-------------------------------
#Normal way to open and close a file
file = open("py_file.txt") #it will give error if no file exist with that name
contents = file.read()
print(contents)
file.close()
#this works same but you don't need to close file in the end
with open("py_file.txt") as file:
contents = file.read()
print(contents)
#when we open without providing a mode, it opens in read only mode
#---------------------Writing in file----------------------------
with open("py_file.txt", mode="w") as file: #we must provide a writing mode for it
file.write("New text.")
#---------------------Append in file----------------------------
with open("py_file.txt", mode="a") as file:
file.write("\nNew text.")
#-------------------------------------------------------------
with open("py_file2.txt", mode="w") as file: #just like in cpp, it creates a new file if there's no file with that name, only when we use Write mode
file.write("\nNew text.") | true |
00260055e446f7cca3815b6c90bfa05ee074d867 | jormarsikiu/PracticasPython | /4-Diccionarios/2_respuesta.py | 762 | 4.375 | 4 | """2)Introducir por teclado una cadena y devuelva un diccionario con la cantidad de apariciones de cada palabra en la cadena. Por ejemplo, si recibe _"que lindo dia que hace hoy"_ debe devolver: `'que': 2, 'lindo': 1, 'dia': 1, 'hace': 1, 'hoy': 1`."""
#!/usr/bin/python
# -*- coding: utf-8 -*-
dic = []
frecuencia = []
cadena=raw_input("Introducir una cadena: " )
lista = cadena.split(' ')
for i in lista:
frecuencia.append(lista.count(i))
#print "keys:", lista
#print "values", frecuencia
dic = dict(zip(lista,frecuencia))
print dic
#Referencias:
#https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python
#https://www.tutorialspoint.com/How-to-create-Python-dictionary-from-list-of-keys-and-values
| false |
5511400414bd3f0d430800655eb9c719883f8ba1 | jormarsikiu/PracticasPython | /2-Listas y Estructuras de Repeticion/3_respuesta.py | 362 | 4.28125 | 4 | """3) Dado la siguiente lista [9,5,1,7,6,3,4,7,2,22,11,85,69,42,45,65] ordenar de menor a mayor y de mayor a menor"""
#!/usr/bin/python
# -*- coding: utf-8 -*-
lista = [9,5,1,7,6,3,4,7,2,22,11,85,69,42,45,65]
l1 = []
l2 = []
l1 = sorted(lista)
l2 = sorted(lista, reverse=True)
print "Lista de menor a mayor: \n", l1
print "Lista de mayor a menor: \n", l2
| false |
0a4e01f59e68f77d5b8b40c0fd1f93f31bb2eba4 | jormarsikiu/PracticasPython | /5-Funciones/2-respuesta.py | 657 | 4.28125 | 4 | """2)Definir una funcion que calcule la longitud de una lista o una cadena dada. (Es cierto que python tiene la funcion len() incorporada, pero escribirla por nosotros mismos resulta un muy buen ejercicio."""
#!/usr/bin/python
# -*- coding: utf-8 -*-
lista=[1,11,8,6,4,3,7,2,14,9]
cadena="Hoy voy a caminar"
def long_lista(lista):
count = 0
for i in lista:
count = count+1
print lista, 'la longitud es: ', count
def long_cadena(cadena):
count = 0
for i in cadena:
count = count+1
print cadena, 'la longitud es: ', count
long_lista(lista)
long_cadena(cadena)
#NOTA: Si la entrada es por la consola el manejo seria con una sola funcion
| false |
6cae48a710c7987a9bb2f99422078f762e0683bd | Qazi-05/WAC | /Day 1/basics.py | 2,576 | 4.40625 | 4 | #print( 'today', 'is', 'the', 'first' , sep='-')
#print("hello",end= ' ')
#print ("world")
'''
multi line
comment
'''
#taking input
# n = input ("Enter your name :")
# print(n)
# variables and data types
# a = 15 #int
# print(a)
# print(type(a)) # type function is used to print type of variable
# b = 10.2 #float
# print(b)
# print(type(b))
# c = True # boolean
# print (c)
# print (type(c))
# d = "today is a sunny day" #str
# print(d)
# print(type(d))
'''
sum = +
substarct = -
mul = *
Div = /
integer div = //
modulo = %
power = **
'''
# a= 5
# b= 3
# print("sum is", a+b)
# print("sub is", a-b)
# print("mul is ",a*b)
# print(" div id ",a/b)
# print("remainder is ",a%b)
# print(" int div is ",a//b)
# s = "today"
# print (5*s)
'''
Logical Operators
#OR
#AND
#NOT
'''
#logical Operators
# Comparison operators
'''
if condition :
statement (consider)
elif condition :
else:
statement(consider)
statement(not consider)
'''
# n=18
# if n > 10 :
# print("larger")
# else :
# print("smaller")
# n = int(input("Enter a number :"))
# if n%3 == 0 :
# print("zero")
# elif n%3 == 1 :
# print("one")
# else :
# print("two")
# n = int(input("Enter a number :"))
# if n%3 == 0 and n%5 == 0 :
# print("FIZZ AND BUZZ")
# elif n%3 == 0 :
# print("FIZZ")
# elif n%5 == 0 :
# print("BUZZ")
# else :
# print("The Number is :",n)
#CALCULATOR
# print("For sum enter 1")
# print("For sub enter 2")
# print("For mul enter 3 ")
# print("For div enter 4 ")
# print("For remainder enter 5 ")
# print("For int div enter 6 ",)
# n = int (input("Enter the choice :"))
# if n > 7 :
# print ("WRONG CHOICE ENTERED")
# a = int(input("Enter 1st Number :"))
# b = int(input("Enter 2nd Number :"))
# if n == 1:
# print(a+b)
# if n == 2:
# print(a-b)
# if n == 3:
# print(a*b)
# if n == 4:
# print(a/b)
# if n == 5:
# print(a%b)
# if n == 6:
# print(a//b)
# leap year
# n = int(input("Enter a year"))
# if n < 0 :
# print("Enter a valid year")
# else :
# print("Valid year entered")
# if n%400 == 0 :
# print("Leap Year")
# elif n% 100 == 0:
# print ("Not a Leap Year")
# elif n%4 == 0 :
# print("Leap Year")
# else :
# print("Not a Leap Year")
# '''
# loops
# #for
# #while
# '''
# i=0 #counter
# while i<10 : #condition
# print('Hello')
# i = i+1 #step size
# print('world')
# print(list(range(5, 10, 2)))
# for i in range (2 ,10,2):
# print(i)
#1.table
n = int(input("enter a number :"))
for i in range (1,11):
print(n*i) | false |
94e5da06b5afd9f2583b47047f37eda1cf7e6efe | amitdshetty/PycharmProjects | /PracticePythonOrg/Solutions/30_Pick_Word.py | 910 | 4.40625 | 4 | """
Problem Statement
This exercise is Part 1 of 3 of the Hangman exercise series. The other exercises are: Part 2 and Part 3.
In this exercise, the task is to write a function that picks a random word from a list of words from the SOWPODS dictionary.
Download this file and save it in the same directory as your Python code. This file is Peter Norvig’s compilation of the dictionary
of words used in professional Scrabble tournaments. Each line in the file contains a single word.
"""
import numpy as np
import random
def main():
file_dir = "/Users/amitshetty/Desktop/Projects/PracticePythonFiles/30 _Pick_Word"
file_name = "SOWPODS.txt"
with open(file_dir + "/" + file_name, "r") as lines:
line = lines.readlines()
# Using numpy random function
#word = np.random.choice(line, 1)
word = random.sample(line, 1)
print(word[0])
if __name__ == '__main__':
main() | true |
63b280c5c5791f4c2a98663fb56cc4c44dc3703f | amitdshetty/PycharmProjects | /PracticePythonOrg/Solutions/13_Fibonacci_Sequence.py | 833 | 4.4375 | 4 | """
Problem Statement
Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
Take this opportunity to think about how you can use functions.
Make sure to ask the user to enter the number of numbers in the sequence to generate.
(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence.
The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
"""
def fibonacci(number):
result = []
first = 0
second = 1
for i in range(number):
first, second = second, first+second
result.append(first)
print(result)
def main():
userInput = int(input('Enter the number of steps for fibonacci to be performed\n'))
fibonacci(userInput)
if __name__ == '__main__':
main() | true |
056c480a7bfca09e83ea61d12575ea46a26ec7c6 | codeBeefFly/bxg_python_basic | /Day03/test/01.输入输出练习.py | 421 | 4.1875 | 4 | """
需求:
收银员输入苹果的价格,单位:元/斤
收银员输入用户购买苹果的重量,单位:斤
计算并输出付款金额
"""
# 收银员输入苹果的价格,单位:元/斤
price = float(input('请输入苹果价格:'))
# 收银员输入用户购买苹果的重量,单位:斤
weight = float(input('请输入购买的重量:'))
# 计算并输出付款金额
money = price*weight
print(money) | false |
cbaffbcb484261206d837878922e062c9d929b0c | NealWhitlock/cs-module-project-algorithms | /moving_zeroes/moving_zeroes.py | 1,239 | 4.21875 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
# def moving_zeroes(arr):
# # Loop through items in array
# for i, num in enumerate(arr):
# # If item zero, pop off list and put at end
# if num == 0:
# arr.append(arr.pop(i))
# # Return array
# return arr
def moving_zeroes(arr):
# Loop through each item in arr with pointers for a single pass
# Left pointer set to first item
left = 0
# Right pointer set to last item
right = len(arr) - 1
# While left is less than right...
while left < right:
# Check if left is zero
if arr[left] == 0:
# If so, and right is non-zero
if arr[right] != 0:
# Swap locations of left and right
arr[left], arr[right] = arr[right], arr[left]
# If left is non-zero...
else:
# Increment left
left += 1
# If right is zero...
if arr[right] == 0:
# Decrement right
right -= 1
return arr
if __name__ == '__main__':
# Use the main function here to test out your implementation
arr = [0, 3, 1, 0, -2]
print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}") | true |
94bc19906a2eeab0ed695d1a408b7c748efc8bd6 | rajashekharreddy/second_repo | /practice/3_tests/8_conversion_system.py | 752 | 4.21875 | 4 | """
This problem was asked by Jane Street.
The United States uses the imperial system of weights and measures, which means
that there are many different, seemingly arbitrary units to measure distance.
There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on.
Create a data structure that can efficiently convert a certain quantity of one
unit to the correct amount of any other unit. You should also allow for additional
units to be added to the system.
"""
class conversion(object):
def __init__(self, val, conver_from, conver_to):
self.val = val
self.conver_from = conver_from
self.conver_to = conver_to
def converrting(self):
pass
conf = {
"cm": 10,
"feet":100,
"meter":200
}.get(input("-->"))
print(conf) | true |
067d6afb89cb1ee5e244eea82fa3e6f2aaf934c8 | beautilut/Algorithm-learning | /Sort.py | 1,694 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#Sort
# 选择排序
# 1.运行时间和输入无关 2.数据移动是最少的
# 交换总次数N 需要N^2/2次比较
def selectSort(array):
length = len(array)
for i in range(length):
min = i
for j in range(min + 1 , length):
if (array[j] < array[min]):
min = j
array[i] , array[min] = array[min] , array[i]
return array
# 插入排序
# 1.平均情况下插入排序需要~N^2/4次比较以及~N^2/4次交换 最坏情况下需要~N^2/2次比较和~N^2/2次交换,最好情况下需要N-1次比较和0次交换
def insertionSort(array):
length = len(array)
for i in range(length):
for j in range(i , 0 , -1):
if(j > 0 and (array[j] < array[j - 1])):
array[j] , array[j-1] = array[j-1],array[j]
return array
#插入排序需要的交换操作和数组中倒置的数量相同,需要的比较次数大于等于倒置的数量,小于等于倒置的数量加上数组的大小再减一。
#对于随机排序的无重复主键的数组,插入排序和选择排序的运行时间是平方级别的。两者之比应该是一个较小的常数。
#希尔排序
#运行时间达不到平方级别 , 代码量很小,且不需要使用额外的内存空间。
def shellSort(array):
N = len(array)
h = 1
while (h < N/3):
h = 3*h + 1
while(h >= 1):
for i in range( h , N):
for j in range(i ,0 , -h):
if(array[j] < array[j-h]):
array[j] , array[j-h] = array[j - h] , array[j]
h = h/3
return array
print (shellSort([0,5,6,3,1,2,9])) | false |
1e2323818c35fae23972cb1c1ec9b532a43abf15 | heartnoxill/cpe213_algorithm | /divide_and_conquer/quicksort_1.py | 977 | 4.21875 | 4 | # Alphabetically QuickSort
__author__ = "Samkok"
def quick_sort(unsorted_list):
# Initiate the hold lists
less = []
equal = []
greater = []
# if list has more than one element then
if len(unsorted_list) > 1:
print("------------------------------")
pivot = unsorted_list[0]
print("Pivot: {}".format(pivot))
for x in unsorted_list:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
elif x > pivot:
greater.append(x)
print("Less: {}".format(less))
print("Equal: {}".format(equal))
print("Greater: {}".format(greater))
return quick_sort(less) + equal + quick_sort(greater)
else:
return unsorted_list
if __name__ == '__main__':
test_list = ['S','O','R','T','I','N','G']
print("Unsorted list: {}".format(test_list))
print("Sorted list: {}".format(quick_sort(test_list)))
| true |
e80156d1329c7813d41d867c878155827cb2dddf | madhumati14/Assignment2 | /Assignment2_1.py | 714 | 4.21875 | 4 | #1.Create on module named as Arithmetic which contains 4 functions as Add() for addition, Sub()
#for subtraction, Mult() for multiplication and Div() for division. All functions accepts two
#parameters as number and perform the operation. Write on python program which call all the
#functions from Arithmetic module by accepting the parameters from user.
import Arithmatic
def main():
no1=int(input("Enter the no1="))
no2=int(input("Enter the no2="))
ans=ass2q1.Add(no1,no2)
print("Addition is =",ans)
ans=ass2q1.Sub(no1,no2)
print("Substraction is=",ans)
ans=ass2q1.Mult(no1,no2)
print("Multiplication is=",ans)
ans=ass2q1.Div(no1,no2)
print("Division is=",ans)
if __name__=="__main__":
main();
| true |
ea564ec3f1fb1b9fb08550bebcf80f38ab3f7320 | rajpravali/Simple_chatbot | /index.py | 1,040 | 4.25 | 4 | from tkinter import * #importing tkinter library used to create GUI applications.
root=Tk() #creating window
def send():#function
send="YOU =>"+e.get()
txt.insert(END,'\n'+send)
if(e.get()=="hello"):
txt.insert(END,'\n'+"Bot => hi")
elif(e.get()=="hi"):
txt.insert(END,'\n'+"Bot => Hello")
elif(e.get()=="how are you"):
txt.insert(END,'\n'+"BOt => Fine thank You, What about you")
elif (e.get() == "Iam good"):
txt.insert(END, '\n' + "BOt => Good to hear!!")
elif(e.get()=="bye"):
txt.insert(END,'\n'+"BOT => Bye!! see you later")
else:
txt.insert(END,'\n'+"Bot => Sorry i didnt get you")
e.delete(0,END)
#creating text area, entry widget and send button
txt=Text(root)
txt.grid(row=0,column=0)
e=Entry(root,width=100)
send=Button(root,text='send', bg='black',fg='white',command=send).grid(row=1,column=1)
e.grid(row=1,column=0)#the grid geometry manager puts the widgets in a 2d table
root.title('simple chatbot') #adding title
root.mainloop() #method
| true |
baa5e4999ca07b308b9c1bc3ef2bc3a603d39beb | jmocay/solving_problems | /linked_list_reverse.py | 1,212 | 4.1875 | 4 | """
Given the head of a singly linked list, reverse it in-place.
"""
class LinkedListNode(object):
def __init__(self, val=None):
self.val = val
self.next = None
def reverse_linked_list(head):
prev = None
curr = head
while curr != None:
curr_next = curr.next
curr.next = prev
prev = curr
curr = curr_next
return prev
"""
Utility function to convert linked list to an array
"""
def linked_list_to_array(head):
arr = []
curr = head
while curr != None:
arr.append(curr.val)
curr = curr.next
return arr
"""
Utility function to create a linked list with n consecutive positive integers
"""
def create_linked_list(n):
head = LinkedListNode(1)
curr = head
for i in range(2, n+1):
curr.next = LinkedListNode(i)
curr = curr.next
return head
if __name__ == '__main__':
for n in range(1, 11):
head = create_linked_list(n)
arr = linked_list_to_array(head)
print("original list:", arr)
head = reverse_linked_list(head)
arr = linked_list_to_array(head)
print("reverse list:", arr)
| true |
0249089bafa357f4e13b093f0730b15e758b69c0 | win911/UT_class | /for_pytest/exercises/2/my_math.py | 259 | 4.21875 | 4 | # my_math.py
def is_multiples_of_three(num):
if num % 3 == 0:
return True
else:
return False
def insert_number(my_list, number_list):
for num in number_list:
if is_multiples_of_three(num):
my_list.append(num) | false |
6412177952d87e19aa29319fe4026098d97cc9f1 | Take-Take-gg/20460065-Ejercicios-Phyton | /Ejercicios-01/Funciones-01.py | 627 | 4.125 | 4 | # Funciones 01
"""
1.- Realiza una función llamada area_rectangulo(base, altura) que devuelva el área
del rectángulo a partir de una base y una altura. Calcula el área de un rectángulo de
15 de base y 10 de altura.
"""
base = 15
altura = 10
def area_rectangulo(base,altura):
res = base * altura
return res
print(f"el area del rectangulo es: {area_rectangulo(base,altura)}")
# Ahora le pedimos los valores a usted
base = float(input("Ingresa el valor de la base: "))
altura = float(input("Ingresa el valor de la altura: "))
print(f"el area del rectangulo con sus valores es: {area_rectangulo(base,altura)}")
| false |
5e7569bd53dd6c635fd783784efca77b4e10b388 | srikanthjg/Functional-Programming | /arg_kwarg.py | 640 | 4.21875 | 4 | #https://www.geeksforgeeks.org/args-kwargs-python/
def myFun(*argv):
for arg in argv:
print (arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
print ""
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks')
print ""
def myFun(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
# Now we can use *args or **kwargs to
# pass arguments to this function :
args = ("Geeks", "for", "Geeks")
myFun(*args)
kwargs = {"arg1" : "Geeks", "arg2" : "for", "arg3" : "Geeks"}
myFun(**kwargs)
| false |
529d42990455129b6d605cb0f34a2d2c4429a7bf | ChiDrummer/PythonCrashCourse | /Chapter4/slices.py | 740 | 4.125 | 4 | #looping through a slice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here's the first three players on my team.")
for player in players[:3]:
print(player.title())
print("\n")
#copying a list
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy Friend's favorite foods are:")
print(friend_foods)
print("\n")
#copying a list with a modification
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy Friend's favorite foods are:")
print(friend_foods)
| false |
8e2815ae5f0f26829be3f7b136c32f68bb835e1e | u104790/hafb2 | /for_loop.py | 328 | 4.34375 | 4 | """
Practice for loops
Keyword: for
"""
cities = ["London", "New York", "Madrid", "Paris", "Ogden"]
# iterate over a list
for city in cities:
print (city)
# iterate over a dictionary
d = {'alice':'801-123-4567',
'pedro': '956-445-78-8966',
'john':'651-321-66-4477'}
for item in d:
print(item, "=>", d[item])
| false |
cf4dff847c730d28b778e5d883c23370a32d9890 | ccrain78990s/Python-Exercise | /0317 資料定義及字典/0317-3-切割.py | 1,485 | 4.15625 | 4 | # 0317 切割
list1=[0,1,2,3,4]
list2=[10,11,12,13,14]
print(list1)
print(list1[3]) #3
print(list2)
print(list2[3]) #13
# 切割 1***
list1=[0,1,2,3,4]
print(list1[0:2]) #[0,1] # 2之前的數字不包含2
print(list1[2:4]) #[2,3]
# 切割 2***
list1=[0,1,2,3,4]
print(list1[1:]) #[1,2,3,4] #1後面的全部數字
print(list1[2:]) #[2,3,4]
print(list1[3:]) #[3,4]
print(list1[3:5]) # ↑ 的另一種寫法 (延伸切割1)
print(list1[4:]) #[4]
# 切割 3***
list1=[0,1,2,3,4]
print(list1[:3]) #[0,1,2] # 3前面的全部數字
print(list1[:4]) #[0,1,2,3]
print(list1[:2]) #[0,1]
# 切割 4***
list1=[0,1,2,3,4]
print(list1[0:3]) #[0,1,2]
print(list1[0:-1]) #[0,1,2,3] # 解釋:____
print(list1[-1:3]) #[]
print(list1[-4:3]) #[1,2]
print(list1[0:-2]) #[0,1,2]
print(list1[:-1]) #[0,1,2,3]
print(list1[-2:]) #[3,4]
print("===練習1===")
list2=[0,1,2,3,4,5,6,7,8,9]
#寫法1
len2=len(list2)
train=list2[:8] #80
print(train)
#寫法2
x=int(len2*0.8)
train=list2[:x] #80
print(train)
test=list2[x:] #20
print(test)
print("===練習2===")
list3=[[0,1,2,3,4],
[10,11,12,13,14],
[20,21,22,23,24],
[30,31,32,33,34],
[40,41,42,43,44]]
print(list3[2][2]) #22
print(list3[3][1]) #31
print(list3[0:2]) #[[0,1,2,3,4],[10,11,12,13,14]]
#list不能這樣用 print(list3[0:2][0:2]) #[[0,1,2,3,4],[10,11,12,13,14]] 請避開 | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.