blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3ccf8a02e53aa1f0a997b898ece4d2ca5916e37c | ApurvaJogal/python_Assignments | /Assignment1/Assignment1_7.py | 469 | 4.1875 | 4 | #Write a program which contains one function that accept one number from user and returns true if number is divisible by 5 otherwise return false.
#Input : 8 Output : False
#Input : 25 Output : True
# Author : Apurva Anil Jogal
# Date : 13th March 2019
def divbyfive(number):
flag=False;
if(number%5==0):
flag=True;
else:
flag=False;
return flag;
num=input("Enter a number\n");
check=divbyfive(num);
if(check == True):
print("True");
else:
print("False");
| true |
c641d986c3221571439cc6a130215ea3f3f3850d | Augutus-Pereghin/GPAcalculator | /main.py | 982 | 4.125 | 4 | # Author: Augustus Perseghin agp5191@psu.edu
# Date: 9/11/2020
# Hwk1
# This program will calculate a student's GPA from 3 classes
def getGradePoint(letterGrade):
GP = 0.0
if letterGrade == 'A':
GP = 4.0
elif letterGrade == 'A-':
GP = 3.67
elif letterGrade == 'B+':
GP = 3.33
elif letterGrade == 'B':
GP = 3.0
elif letterGrade == 'B-':
GP = 2.67
elif letterGrade == 'C+':
GP = 2.33
elif letterGrade == 'C':
GP = 2.0
elif letterGrade == 'D':
GP = 1.0
return GP
def run():
i = 0
scores = [0, 0, 0]
weights = [0, 0, 0]
totalGP = 0
totalWeight = 0
while i != 3:
scores[i] = float(getGradePoint(input(f"Enter your course {i + 1} letter grade: ")))
weights[i] = float(input(f"Enter your course {i + 1} credit: "))
print(f"Grade point for course {i+1} is: {scores[i]}")
totalGP += scores[i]*weights[i]
totalWeight += weights[i]
i += 1
print(f"Your GPA is: {totalGP/totalWeight}")
if __name__ == "__main__":
run() | false |
dd67946a2672e5480eafd0e8850605a964c7d6fb | urveshpal/RockPaperScissorGame | /rockPaperScissorGame.py | 1,359 | 4.15625 | 4 | # Basic Game Project in Python
def rock_paper_scissor(num1,num2,bit1,bit2):#Creating functiom
p1=int(num1[bit1])%3
p2=int(num2[bit2])%3
if(player1[p1]==player2[p2]):
print("Draw")
elif(player1[p1]=="Rock" and player2[p2]=="Scissor"):
print("Player_1 win(Rock)!!")
elif(player1[p1]=="Paper" and player2[p2]=="Rock"):
print("Player_1 win(Paper)!!")
elif(player1[p1]=="Scissor"and player2[p2]=="Paper"):
print("Player_1 win(Scissor)!!")
elif(player1[p1]=="Paper"and player2[p2]=="Scissor"):
print("Player_2 win(Scissor)")
elif(player1[p1]=="Rock" and player2[p2]=="Paper"):
print("Player_2 win(Paper)!!")
elif(player1[p1]=="Scissor" and player2[p2]=="Rock"):
print("Player_2 win (Rock)!!" )
player1={0:'Rock',1:'Paper',2:'Scissor'}# This is two data dicsnary
player2={0:'Paper',1:'Rock',2:'Scissor'}
while(1):
num1=input("Player_1 enter your choice:")
num2=input("Player_2 enter your choice:")
bit1=int(input("Player_1 enter the secrate position:"))# Secrate position of value
bit2=int(input("Player_2 enter the secrate position:"))
rock_paper_scissor(num1,num2,bit1,bit2)#Calling the function
ch=input("Do you continue?(y/n):")
if(ch=='n'):# If input ch equal to n ,then break the iteration
break
| false |
27120cb77e589e616f9c57e62a1ca814307f4523 | abhisheksingh75/Practice_CS_Problems | /Math/Sum_of_pairwise_Hamming_Distance.py | 1,711 | 4.21875 | 4 | """https://www.interviewbit.com/problems/sum-of-pairwise-hamming-distance/
Hamming distance between two non-negative integers is defined as the number of positions at which the corresponding bits are different.
For example,
HammingDistance(2, 7) = 2, as only the first and the third bit differs in the binary representation of 2 (010) and 7 (111).
Given an array of N non-negative integers, find the sum of hamming distances of all pairs of integers in the array.
Return the answer modulo 1000000007.
Example
Let f(x, y) be the hamming distance defined above.
A=[2, 4, 6]
We return,
f(2, 2) + f(2, 4) + f(2, 6) +
f(4, 2) + f(4, 4) + f(4, 6) +
f(6, 2) + f(6, 4) + f(6, 6) =
0 + 2 + 1
2 + 0 + 1
1 + 1 + 0 = 8
"""
import math
class Solution:
# @param A : tuple of integers
# @return an integer
def hammingDistance(self, A):
binary_no_list = []
max_len = 0
sum = 0
if len(A) == 1:
return 0.
for ele in A:
binary_no = []
if ele != 0:
while(ele>0):
binary_no.append(str(ele%2))
ele = int(math.floor(ele/2))
if len(binary_no) > max_len:
max_len = len(binary_no)
else:
binary_no.append('0')
binary_no_list.append(binary_no)
for i in range(0, max_len):
x, y= 0, 0
for ele in binary_no_list:
if len(ele) <= i:
x +=1
elif ele[i] == '0':
x +=1
elif ele[i] == '1':
y +=1
sum += ((x*y)<<1)
return sum%1000000007
| true |
d74d9e1e38484d2abf23a1084bc0ea4f7ce2ce97 | abhisheksingh75/Practice_CS_Problems | /Arrays/Wave_Array.py | 726 | 4.25 | 4 | """https://www.interviewbit.com/problems/wave-array/
Given an array of integers, sort the array into a wave like array and return it,
In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
Example
Given [1, 2, 3, 4]
One possible answer : [2, 1, 4, 3]
Another possible answer : [4, 1, 3, 2]
NOTE : If there are multiple answers possible, return the one thats lexicographically smallest.
"""
class Solution:
# @param A : list of integers
# @return a list of integers
def wave(self, A):
lenOfA = len(A)
A.sort()
for i in range(len(A)):
if (i+1)%2 != 0 and (i+1) < lenOfA:
A[i], A[i+1] = A[i+1], A[i]
return A
| true |
2beb75f42b1257cc18d2a348d84f1e1455396666 | abhisheksingh75/Practice_CS_Problems | /Hashing/Anagrams.py | 1,343 | 4.125 | 4 | """
Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the index in the original list. Look at the sample case for clarification.
Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', formed from 'rasp' Note: All inputs will be in lower-case.
Example :
Input : cat dog god tca
Output : [[1, 4], [2, 3]]
cat and tca are anagrams which correspond to index 1 and 4. dog and god are another set of anagrams which correspond to index 2 and 3. The indices are 1 based ( the first element has index 1 instead of index 0).
Ordering of the result : You should not change the relative ordering of the words / phrases within the group. Within a group containing A[i] and A[j], A[i] comes before A[j] if i < j.
"""
class Solution:
# @param A : tuple of strings
# @return a list of list of integers
def anagrams(self, A):
ans = []
dic_ele = {}
dic_indx = {}
for i in range(len(A)):
ele = "".join(sorted(A[i]))
#print(ele)
if ele in dic_ele:
dic_ele[ele].append(i+1)
else:
dic_ele[ele] = [i+1]
for key in dic_ele:
ans.append(dic_ele[key])
return ans
| true |
704b3add9c24d1535f9107451ef57007129bef81 | abhisheksingh75/Practice_CS_Problems | /Queue/Gas Station.py | 2,276 | 4.1875 | 4 | """
Given two integer arrays A and B of size N. There are N gas stations along a circular route, where the amount of gas at station i is A[i]. You have a car with an unlimited gas tank and it costs B[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the minimum starting gas station's index if you can travel around the circuit once, otherwise return -1. You can only travel in one direction. i to i+1, i+2, ... n-1, 0, 1, 2.. Completing the circuit means starting at i and ending up at i again.
Input Format
The first argument given is the integer array A.
The second argument given is the integer array B.
Output Format
Return the minimum starting gas station's index if you can travel around the circuit once, otherwise return -1.
For Example
Input 1:
A = [1, 2]
B = [2, 1]
Output 1:
1
Explanation 1:
If you start from index 0, you can fill in A[0] = 1 amount of gas. Now your tank has 1 unit of gas. But you need B[0] = 2 gas to travel to station 1.
If you start from index 1, you can fill in A[1] = 2 amount of gas. Now your tank has 2 units of gas. You need B[1] = 1 gas to get to station 0. So, you travel to station 0 and still have 1 unit of gas left over. You fill in A[0] = 1 unit of additional gas, making your current gas = 2. It costs you B[0] = 2 to get to station 1, which you do and complete the circuit.
"""
class Solution:
# @param A : tuple of integers
# @param B : tuple of integers
# @return an integer
def canCompleteCircuit(self, A, B):
start,end = 0,1
total = (A[start]-B[start])
if len(A) == 1:
if total >= 0:
return 0
else:
return -1
count = 0
while(start<len(A) and count != len(A)):
if total < 0:
total -=((A[start]-B[start]))
start += 1
count = 0
else:
total +=((A[end]-B[end]))
end = (end+1)%len(B)
count += 1
if count == len(A) and total >= 0:
return start
else:
return -1
| true |
1da33759c947b871b403a47a23e0622e2e2fec74 | itsfk/Python-Assignments | /Excercises/excercise3.py | 2,868 | 4.125 | 4 | # Excercise 3.1
# friendlist=["Faiz","Shoaib","Farwa"]
# print(friendlist[0])
# print(friendlist[1])
# print(friendlist[2])
# Excercise 3.2
# friendlist=["Faiz","Shoaib","Farwa"]
# for x in friendlist:
# print("Hello "+x)
# Excercise 3.3
# car=["Honda", "Toyata","BMW"]
# for car in car:
# print("I would like to own "+car)
# Excercise 3.4
# invites=["Mom","Dad","Brother"]
# for invites in invites:
# print(invites+ " You are invited at the dinner")
# Excercise 3.5
# invites=["Mom","Dad","Brother"]
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# print("Brother can not make it to dinner")
# invites[2] = "Sister"
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# Excercise 3.6
# invites=["Mom","Dad","Brother"]
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# print("Brother can not make it to dinner")
# invites[2] = "Sister"
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# print("I have found a bigger table")
# invites.insert(0,"Shoaib")
# invites.insert(2,"Farwa")
# invites.append("Ashir")
# for invites in invites:
# print(invites+ " You are invited")
# Excercise 3.7
# invites=["Mom","Dad","Brother"]
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# print("Brother can not make it to dinner")
# invites[2] = "Sister"
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# print("I have found a bigger table")
# invites.insert(0,"Shoaib")
# invites.insert(2,"Farwa")
# invites.append("Ashir")
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# print(invites[2]+ " You are invited ")
# print(invites[3]+ " You are invited ")
# print(invites[4]+ " You are invited ")
# print(invites[5]+ " You are invited ")
# print("Can only invite two people")
# a=invites.pop()
# print(a+ " Sorry could not invite you")
# a=invites.pop()
# print(a+ " Sorry could not invite you")
# a=invites.pop()
# print(a+ " Sorry could not invite you")
# a=invites.pop()
# print(a+ " Sorry could not invite you")
# print(invites[0]+ " You are invited ")
# print(invites[1]+ " You are invited ")
# del invites[0]
# print(invites)
# del invites[0]
# print(invites)
# Excercise 3.8
# cities=["Toronto","Karachi","Sydney","Perth","London"]
# print(cities)
# print(sorted(cities))
# print(cities)
# cities.reverse()
# print(cities)
# cities.reverse()
# print(cities)
# cities.sort()
# print(cities)
# Excercise 3.9
# cities=["Toronto","Karachi","Sydney","Perth","London"]
# print(len(cities))
| false |
e766d68056163bed1040f7a9581c93bac48d9561 | datafined/homework_gb | /lesson_4/task_3.py | 350 | 4.21875 | 4 | # Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
# Подсказка: использовать функцию range() и генератор.
print([x for x in range(20, 241) if not x % 20 or not x % 21])
| false |
547f9845a1aba256910b3ff29a78d380d3538b7f | datafined/homework_gb | /lesson_1/task_1.py | 591 | 4.375 | 4 | # Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные,
# выведите на экран.
name = 'Alex'
age = 19
city = 'Moscow'
print(name, age)
print(city)
user_str = input('Введите строку: ')
user_float = int(input('Введите целое число: '))
print(f'Вы ввели строку: {user_str}')
print(f'Вы ввели число: {user_float}')
| false |
0f9206f0534d2d6d5c49070b62155fa3b9b6da48 | Ankygurjar/DSA-Course | /Mathematics/factorial.py | 251 | 4.21875 | 4 | '''
Python program to find the factorial of a number
Create a recursive funtion that runs till n becomes zero and add n to n - 1 in every iteration
'''
def factorial( n ):
if n == 0:
return 0
return n * factorial(n-1)
factorial(4) # => 24
| true |
3576e3d7f98403f1d1d0af2e8f93190653918f78 | ZJmitch/Python-Code-Samples- | /Area of a circle.py | 221 | 4.46875 | 4 | CONSTANT_PI = 3.14159
radius = int(input("Enter the radius of the circle: "))
area = CONSTANT_PI * radius**2
print("The area of the circle is", area)
#Justin Mitchell
#1/31/2021
#Program computes the area of a circle
| true |
56e22cf8b032944bd9303818f14dee4a802eb59f | kmangub/ctci_questions | /chapter_1/array_and_strings_1_1.py | 845 | 4.375 | 4 | # 1.1 Implement an algorithm to determine if a string has all unique characters. what if you cannot use aditional data structures
#Input takes in a string
#output is True or False
#Algorithm. First we want to iterate through each character of the string.
def unique_characters(string):
each_char = []
unique = True
# We want to iterate through the string
for char in string:
# The if statement checks to see if the character exists in our list and will change the status of unique
if char in each_char:
unique = False
# appends the char to the array
else:
each_char.append(char)
return unique
# tests
print(unique_characters('abcde'))
#Solution
#Clarify if the string is ASCII or Unicode string
# American Standard Code for Information Interchange (ASCII) is code used to represent characters | true |
1e8863f665894fadc3a439a884a337127789299d | GundetiGnanika-20186026/cspp1 | /cspp1-practice/m5/guess_my_number.py | 1,207 | 4.21875 | 4 | '''
Auther:Gnanika
Date:3 August 2018
'''
def main():
'''guessing number'''
lo_w = 0
h_i = 100
print("please think of a number between 0 and 100")
print("Enter 'h' to indicate the guess is too high")
print("Enter 'l' to indicate the guess is too low")
print("Enter 'c' to indicate I guessed correctly")
print("is your secret number 50?")
m_i = (lo_w + h_i)//2
print(m_i)
i = input()
while m_i <= 100:
if i == 'h':
h_i = m_i
m_i = (lo_w+h_i)//2
print("is your secret number "+str(m_i)+"?")
i = input()
elif i == 'l':
lo_w = m_i
m_i = (lo_w+h_i)//2
print("is your secret number "+str(m_i)+"?")
i = input()
elif i == 'c':
print("Game Over. I successfully guessed your secret number")
break
else:
print("sorry,I did not understand your input")
print("Enter 'h' to indicate the guess is too high")
print("Enter 'l' to indicate the guess is too low")
print("Enter 'c' to indicate I guessed correctly")
i = input()
if __name__ == "__main__":
main()
| true |
b348a812b91ee88e25f4e4a1213f03d8a9e4e39b | mirgit/database-program-refactoring | /Table.py | 2,716 | 4.125 | 4 | """/**
* The definition of a table in a schema.
*/"""
class Table:
"""/**
* Constructs the definition of a table with the given name
* and columns with the given primary and foreign keys.
*
* @param name the name of the table
* @param columns the columns in the table -- list of tuple (col_name, col_type)
* @param primaryKey the primary key of the table -- string
* @param foreignKeys Dict {(src_table_name, src_col_name): (dest_table_name, dest_col_name)}
*/"""
def __init__(self, name, columns, primaryKey, foreignKeys):
self.name = name
self.columns = columns
self.primaryKey = primaryKey
self.foreignKeys = foreignKeys
self.data = []
def __str__(self) :
return " ".format("TableDef(%s, %s, %s, %s)", self.name, self.columns, self.primaryKey, self.foreignKeys)
def insert(self,row): # row is dictionary of attrs:values
if not self.primaryKey in row.keys(): # generate new primary key
i = 0
while i < len(self.columns):
if self.columns[i][0] == self.primaryKey:
break
max_prim_key = 0
for r in self.data:
max_prim_key = max(max_prim_key, r[i])
row[self.primaryKey] = max_prim_key + 1
new_row = []
for col, t in self.columns:
if col in row.keys():
new_row.append(row[col])
else:
new_row.append(None)
self.data.append(new_row)
def delete(self, predicate): # {a_i:v_i, ...}
indices = {}
for i in range(len(self.columns)):
if self.columns[i][0] in predicate.keys():
indices[self.columns[i][0]] = i
for ind in range(len(self.data)):
row = self.data[ind]
match = True
for attr in predicate.keys():
if row[indices[attr]] != predicate[attr]:
match = False
if match:
del (self.data[ind])
def update(self, predicate, values): # predicate:{a_i:v_i, ...}, vals:{a_j:v_j, ...}
indices = {}
for i in range(len(self.columns)):
if self.columns[i][0] in predicate.keys() or self.columns[i][0] in values.keys():
indices[self.columns[i][0]] = i
for ind in range(len(self.data)):
row = self.data[ind]
match = True
for attr in predicate.keys():
if row[indices[attr]] != predicate[attr]:
match = False
if match:
for attr in values.keys():
self.data[ind][attr] = values[attr]
| true |
4399d6b24e1613d4d0b4c85a5c8672516c394a55 | Kawaljeet18/Python-Programs | /PASS_GEN.py | 638 | 4.25 | 4 | # PASSWORD GENERATOR
# THIS PROGRAM WILL HELP TO GENERATE PASSWORD OF YOUR LENGTH
# IT WILL TAKE THE LENGTH OF THE PASSWORD DESIRED BY THE USER.
# AND THEN FROM ITS SET OF ALPHABETS AND SPECIAL CHARACTERS IT WILL SUGGEST YOU A PASSWORD.
# QUITE USEFUL
import random
import string
def ps_gen(size=8,chars=string.ascii_letters + string.digits + string.punctuation):
return " ".join(random.sample(chars, size))
# return " ".join(random.choice(chars) for _ in range(size))
size = int(input("Please Enter Strength Of Your Password i.e From 0-9 :"))
password = ps_gen(size)
print("Your Password Should Be:",password) | true |
fa1866591d7f1eee9118fbbf8d462f2528ec6530 | zVelto/Python-Basico | /aula14/aula14.py | 793 | 4.15625 | 4 | import re
def is_float(val):
if isinstance(val, float): return True
if re.search(r'^\-{,1}[0-9]+\.{1}[0-9]+$', val): return True
return False
def is_int(val):
if isinstance(val, int): return True
if re.search(r'^\-{,1}[0-9]+$', val): return True
return False
def is_number(val):
return is_int(val) or is_float(val)
num1 = input('Digite um número: ')
num2 = input('Digite outro número: ')
"""
# isnumeric isdigit isdecimal
if is_number(num1) and is_number(num2):
num1 = int(num1)
num2 = int(num2)
print(num1 + num2)
else:
print('Não pude converter os números para realizar contas')
"""
try:
num1 = int(num1)
num2 = int(num2)
print(num1 + num2)
except:
print('Não pude converter os números para realizar contas')
| false |
bd3926ee51d1fbe352f3c4dd1aa738fdacd3f03e | bennythejudge/topN | /topN.py | 2,555 | 4.125 | 4 | #!/usr/bin/env python
import sys
def usage():
print "Usage: {} <filename> <N>".format(sys.argv[0])
def find_smallest(array):
smallest = 0
smallest_at = 0
for n,i in enumerate(array):
#print "find_smallest i {} n {}".format(i,n)
#print "find_smallest Index {} considering {} smallest {} smallest_at {}".format(n,array[n],smallest,smallest_at)
if n == 0:
smallest = array[n]
smallest_at = n
#print "find_smallest: first time"
elif array[n] < smallest:
#print "find_smallest: found {} which is smaller then smallest {}".format(array[n],smallest)
smallest = array[n]
smallest_at = n
#print "find_smallest: returning smallest {} smallest_at {}".format(smallest,smallest_at)
return smallest, smallest_at
def main():
entries = []
if len(sys.argv) == 3:
filename = sys.argv[1]
N = int(sys.argv[2])
else:
usage()
exit(1)
# if N is > than ??? maybe it should go for external sort?
c = 0
smallest = 0
smallest_at = 0
first_time = True
with open(filename, "r") as f:
for line in f:
#print "read {}".format(int(line))
if first_time:
#print "first time"
first_time = False
smallest = int(line)
smallest_at = 0
else:
if c<N:
#print "now loading the {} elements in array and looking for the smallest".format(N)
entries.append(int(line))
if int(line) < smallest:
smallest = int(line)
smallest_at = c
#print "smallest {} index {}".format(smallest, smallest_at)
c += 1
continue
else:
#print "now in the last part of the loop"
#print "considering read value {} and smallest {}".format(int(line),smallest)
if int(line) > smallest:
#print "found bigger value {} than smallest {}".format(int(line),smallest)
#print "entries before {}".format(entries)
entries[smallest_at] = int(line)
#print "entries before {}".format(entries)
# now find the new smallest
#print "before searching the smallest {} {}".format(smallest,smallest_at)
smallest, smallest_at = find_smallest(entries)
#print "after searching the smallest {} {}".format(smallest,smallest_at)
f.close()
print entries
entries.sort(reverse=True)
print entries
if __name__ == "__main__":
main()
| false |
bf01f61526b04ab71ca9a65947367e89712a663f | grantpalmersamples/property_wrapper | /lib/property_wrapper/nested_lookup.py | 2,785 | 4.125 | 4 | """
Use lists of keys and indices to access certain properties in
subscriptable structures.
Example:
data = {'dk0': ['li0', ('ti0', 'ti1')], 'dk1': 'dv1'}
v = nget(data, ['dk0', 1, 0])
v is now 'ti0'.
"""
from pprint import pformat
def _nget(data: any, path: list) -> tuple:
"""
Get the furthest value along a given key path in a subscriptable
structure.
:param data: the subscriptable structure to examine
:param path: the lookup path to follow
:return: tuple of value at furthest valid key, furthest valid
path
"""
idx = 0
for key in path:
try:
data = data[key]
idx += 1
except LookupError:
break
return data, path[:idx]
def path_valid(data: any, path: list) -> bool:
"""
Determine whether it's possible to follow the key path in a
subscriptable structure.
:param data: the subscriptable structure to examine
:param path: the lookup path to verify
:return: whether the lookup path exists within data
"""
return len(path) == len(_nget(data, path)[1])
def nget(data: any, path: list) -> any:
"""
Get the value at the end of the key path in a subscriptable
structure.
:param data: the subscriptable structure to examine
:param path: the lookup path to follow
:return: the value at the end of the key path
"""
val, valid_path = _nget(data, path)
if len(path) == len(valid_path):
return val
else:
raise LookupError('Failed to find key \'{}\' at path {} in the '
'following data:\n{}.'.format(path[len(valid_path)],
valid_path,
pformat(data)))
def nset(data: any, path: list, val: any) -> None:
"""
Set the value at the end of the key path in a subscriptable
structure.
:param data: the subscriptable structure to examine
:param path: the lookup path to follow
:param val: the new value to assign
"""
try:
nget(data, path[:-1])[path[-1]] = val
except TypeError as e:
raise TypeError('Cannot set value at path {} in the following '
'data:\n{}.'.format(path, pformat(data))) from e
def ndel(data: any, path: list) -> None:
"""
Delete the value at the end of the key path from the subscriptable
structure containing it.
:param data: the subscriptable structure to examine
:param path: the lookup path to follow
"""
try:
del(nget(data, path[:-1])[path[-1]])
except TypeError as e:
raise TypeError('Cannot delete value at path {} in the following '
'data:\n{}.'.format(path, pformat(data))) from e
| true |
bacdbdc6e5453500880f722a99d831b56fb8a6f4 | manoloah/python_learning | /lists_python.py | 1,029 | 4.5625 | 5 | #lists: matrix[row][column], row 1 starts at index o
#lists can have negative indexes:
list = ['potter','rooney','scholes']
print(list[-1]) # outputs the last value in list
#slices of lists list[startitem:enditem-1]
print(list[0:3])
i = 5
for i in range(4):
print(i+1)
#to iterate over a list of values
for i in range(len(list)):
print(list[i])
#assigning variables from a lists:
player_1,player_2,player_3 = list
print(player_3)
list.insert(4,'ronaldo') #append does the same but adds it at the end, remove()
print(list)
list.sort()
print(list)
list.sort(reverse=True)
#Many of the things you can do with lists can also be done with strings: indexing; slicing; and using them with for loops, with len(), and with the in and not in operators. To see this, enter the following into the interactive shell
name = 'Sophie' #tupple is treating a string as a list (example below)
for i in name:
print('****'+i+'****')
#But the main way that tuples are different from lists is that tuples, like strings, are immutable
| true |
3c126f696c3860b7789e1965781383dc1a8be444 | ComicShrimp/Metodos-de-Calculo-Numerico | /Python/diferencas_finitas.py | 566 | 4.21875 | 4 | # Created by: Mário Victor Ribeiro Silva
import math
# função que retorna o valor da equação utilizado no problema
def funcao(x):
return math.pow(x, 3)
# Obtem os valores necessários
initp = float(input('Valor do Ponto inicial : '))
h = float(input('Tamanho do Passo: '))
# Retorna os 3 tipos de diferenças finitas
print('Metodo Progressivo : {:.6f}'.format((funcao(initp + h) - funcao(initp)) / h))
print('Metodo Regressivo : {:.6f}'.format((funcao(initp) - funcao(initp - h)) / h))
print('Metodo Central : {:.6f}'.format((funcao(initp + h) - funcao(initp - h)) / 2 * h))
| false |
8cfa2c539cada53033fd06f24ffa14dfc8bbbaea | jeanwisotscki/Python-Mundo-2 | /ex071.py | 1,129 | 4.15625 | 4 | '''
Exercício Python 071: Crie um programa que simule o funcionamento
de um caixa eletrônico. No início, pergunte ao usuário qual será
o valor a ser sacado (número inteiro) e o programa vai informar
quantas cédulas de cada valor serão entregues. OBS:
considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.
'''
# Cabeçalho
print('='*30)
print("{:^30}".format("CAIXA ELETRÔNICO"))
print('='*30)
# Solução
saque = int(input('Digite o valor do saque: '))
total = saque # Montante total que será decomposto
nota = 50 # Tirar 50 reais do montante
totalnotas = 0
while True:
if total >= nota:
total -= nota
totalnotas += 1
else:
if totalnotas > 0:
print('Total de {} notas de R$ {}' .format(totalnotas, nota))
if nota == 50:
nota = 20
elif nota == 20:
nota = 10
elif nota == 10:
nota = 1
totalnotas = 0
if total == 0:
break
print('~'*30)
print('{:-^30}'.format(' BANCO BOX '))
print('~'*30) | false |
1fac2fbdbf6683f33eb2a1f3c4cc692832161769 | jaden7856/python_programming_stu | /mycode/4_list/list_stack.py | 627 | 4.28125 | 4 | '''
Stack과 Queue 를 List 로 작성한다.
'''
stack_list = [1, 2, 3]
stack_list.append(5)
stack_list.extend([10, 20])
print(stack_list)
# LIFO
stack_list.pop()
print(stack_list)
stack_list.pop()
print(stack_list)
# FIFO
queue_list = [10, 20, 30]
queue_list.pop(0)
print(queue_list)
# tuple
my_tuple = tuple([10, 30, 40])
my_tuple2 = (20, 30, 40)
print(type(my_tuple), type(my_tuple2))
print(my_tuple[2], my_tuple2[0:2], my_tuple * 2)
my_int = (10)
my_tuple3 = (10, )
print(type(my_int), type(my_tuple3))
# set 중복을 허용하지 않음
my_set = set([1, 2, 3, 1, 2, 3])
print((type(my_set), my_set))
my_set.add(1) | false |
e365804462a044ebaa014ff2c46a4960de60af21 | Chalithya/python_learning | /lengthConverter.py | 1,488 | 4.125 | 4 | length = float(input("Enter the length: "))
type = input('''
Milimeters : mm
Centimeters : c
Meters : m
Kilometers : km
Enter the relevant symbol for your input unit : ''')
values = []
if type.upper()=='MM':
values.append(length)
values.append(length/10)
values.append(length/10**3)
values.append(length/10**6)
type =' mm'
elif type.upper()== 'C':
values.append(length*10)
values.append(length)
values.append(length/10**2)
values.append(length/10**5)
type = ' cm'
elif type.upper()== 'M':
values.append(length*10**3)
values.append(length*10**2)
values.append(length)
values.append(length/10**3)
type = ' m'
elif type.upper()== 'KM':
values.append(length*10**6)
values.append(length*10**5)
values.append(length*10**3)
values.append(length)
type = ' km'
else :
print("Type mismatch")
answerType = input('''
Milimeters : mm
Centimeters : c
Meters : m
Kilometers : km
Enter your output option: ''')
if answerType.upper()=='MM':
print(f'{str(length)+type} = {str(values[0])} mm')
elif answerType.upper()== 'C':
print(f'{str(length)+type} = {str(values[1])} cm')
elif answerType.upper()== 'M':
print(f'{str(length)+type} = {str(values[2])} m')
elif answerType.upper()== 'KM':
print(f'{str(length)+type} = {str(values[3])} km')
else :
print("Type mismatch")
# print(values[0])
# print(values[1])
# print(values[2])
# print(values[3])
| true |
c91e542f1968c252b8aaf474b8946255b33fe0f5 | pydevjason/LinkedIn-repo | /temp_conversion.py | 1,148 | 4.59375 | 5 | """convert_cel_to_far() which takes one float parameter representing
degrees Celsius and returns a float representing the same temperature
in degrees Fahrenheit using the following formula:
F = C * 9/5 + 32"""
"""convert_far_to_cel() which take one float parameter representing
degrees Fahrenheit and returns a float representing the same temperature in degrees Celsius using the following formula:
C = (F - 32) * 5/9"""
def cel_to_far(c_deg):
f = (c_deg * 9 / 5) + 32
return f"{c_deg} degrees C is {f:.1f} degrees F"
def far_to_cel(f_deg):
c = (f_deg - 32) * 5 / 9
return f"{f_deg} degrees F is {c:.1f} degrees C"
def start_program():
start = True
while start:
try:
cels = float(input("enter a temp in degrees C: "))
cel_temp = cel_to_far(cels)
print(cel_temp)
print()
far = float(input("enter a temp in degrees F: "))
far_temp = far_to_cel(far)
print(far_temp)
start = False
except ValueError:
print("you must enter a numeric value")
start_program()
| true |
78f43343d1ee2174759172c335f1c57aabf2d409 | Vidhyalakshmi-sekar/LetsUpgrade_PythonAssignment | /pilot.py | 299 | 4.15625 | 4 | # getting altitude as input
while True:
altitude = int(input("Please enter the altitude: "))
if altitude <= 1000:
print('Safe to land')
break
elif 1000 < altitude <= 5000:
print('Bring down to 1000')
else:
print('Go around and try later')
| true |
cd7d8d34a560b50f425954fb24845cb6675303e6 | SeemannMx/pythonTutorial | /whileTest.py | 1,011 | 4.125 | 4 | # while loop
x = 0
while x < 10:
print("test while loop")
print(x)
x = x + 1
# for loop
print("")
print("List of programm languages")
print("--------------------------")
y = [ "C","\tC++","\t\tjava", "\t\t\tgo", "\t\t\t\tphyton", "\t\t\t\t\ttypescript"]
# languages is new variable which has not been created before
for language in y:
print(language)
print("")
# range funtion
print("for / range ")
print("--------------------------")
for i in range(5):
print(i)
print("")
# i > 5 & i < 10
for i in range(5,10):
print(i)
print("")
# count up in steps
for i in range(0,10, 2):
print(i)
print("")
# count down in steps
for i in range(10,5,-1):
print(i)
print("")
# run through list
print("List of fruits")
print("--------------------------")
fruits = ["\t\tapple", "\t\torange", "lime", "kiwi", "\t\tstrawberry", "\t\tbanana"]
for j in range(len(fruits)):
print(fruits[j])
print("")
def functionToTest():
print("function from whileTest")
| false |
72268bfc50eb5d723f9d401225822382a4e9fc6e | Tawncat/Python4E | /2_5.py | 289 | 4.46875 | 4 | # Write a program which prompts the user for a Celcius temperature,
# convert the temperature to Fahrenheit, and print out the converted temperature.
temp = input("Enter a temperature in Celcius: ")
fahrenheit = (float(temp) * 1.8) + 32
print("Temperature in Fahrenheit is: ",fahrenheit)
| true |
d2a310c8b9afbc753c3668a2a921def15ec82af8 | Tawncat/Python4E | /11_1.py | 451 | 4.125 | 4 | # Write a simple program to simulate the operation of the grep command on Unix.
# Ask the user to enter a regular expression and count the number of lines that
# matched the regular expression:
import re
regex = input("Enter a regular expression:")
fhand = open('mbox.txt')
linecount = 0
for line in fhand:
line = line.rstrip()
if re.search(regex, line):
linecount += 1
print(fhand, 'had', linecount, 'lines that matched', regex)
| true |
8ae5348bea48765506cd4903283c57d35d2297c5 | ryangleason82/DailyCoding | /June4th.py | 622 | 4.125 | 4 | # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
# Given this implementation of cons:
# def cons(a, b):
# def pair(f):
# return f(a, b)
# return pair
# Implement car and cdr
def cons(a, b):
return lambda m: m(a, b)
def car(cons):
return cons(lambda a, b: a)
def cdr(cons):
return cons(lambda a, b: b)
print(car(cons(3, 4)))
# The solution they provided
def car1(pair):
return pair(lambda a, b: a)
def cdr1(pair):
return pair(lambda a, b: b)
| true |
5c0e828e61e3ae87dda8750404bb34308ee7ca6c | petehwu/python_practice | /sorting_algos.py | 2,659 | 4.125 | 4 | #!/Users/pwu/anaconda/bin/python3
""" shebang for linux #!/usr/bin/env python3
binary search tree implementation
"""
def bubbleSort(arr):
""" bubble sort algo
"""
swapped = True
print("before bubble sort {}".format(arr))
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = True
print("after bubble sort {}".format(arr))
def quickSort(arr):
""" quick sort entry point
"""
print("before quickSort {}".format(arr))
rqs(arr, 0, len(arr) - 1)
print("after quickSort {}".format(arr))
def rqs(arr, begin, end):
""" recursive quick sort algo
"""
if begin < end:
pIndex = findPivot(arr, 0, end)
rqs(arr, 0, pIndex - 1)
rqs(arr, pIndex + 1, end)
def findPivot(arr, begin, end):
pIndex = begin
pVal = arr[end]
while begin < end:
if arr[begin] < pVal:
arr[begin], arr[pIndex] = arr[pIndex], arr[begin]
pIndex += 1
begin += 1
arr[begin], arr[pIndex] = arr[pIndex], arr[begin]
return pIndex
def mergeSort(arr):
""" entry point for merge sort
"""
print("before merge sort {}".format(arr))
rms(arr)
print("after merge sort {}".format(arr))
def rms(arr):
"""recursive merge sort algo
"""
mid = len(arr) // 2
if mid > 0:
left = arr[:mid]
right = arr[mid:]
rms(left)
rms(right)
merge(arr, left, right)
def merge(arr, left, right):
""" merge left and right for merge sort
"""
ai = 0
li = 0
ri = 0
while li < len(left) and ri < len(right):
if left[li] < right[ri]:
arr[ai] = left[li]
li += 1
else:
arr[ai] = right[ri]
ri += 1
ai += 1
while li < len(left):
arr[ai] = left[li]
li += 1
ai += 1
while ri < len(right):
arr[ai] = right[ri]
ri += 1
ai += 1
if __name__ == '__main__':
bubbleSort([50, 90, 23, 56, 1, 3, 7, 45, 7, 8])
quickSort([50, 90, 23, 56, 1, 3, 7, 45, 7, 8])
mergeSort([50, 90, 23, 56, 1, 3, 7, 45, 7, 8])
print("++++++++++++++++")
bubbleSort([1, 2, 3])
quickSort([1, 2, 3])
mergeSort([1, 2, 3])
print("++++++++++++++++")
bubbleSort([1])
quickSort([1])
mergeSort([1])
print("++++++++++++++++")
bubbleSort([1, 2])
quickSort([1, 2])
mergeSort([1, 2])
print("++++++++++++++++")
bubbleSort([3, 2, 1])
quickSort([3, 2, 1])
mergeSort([3, 2, 1])
print("++++++++++++++++")
| false |
6bfbed10f2be00a9cd038e8db238272c5ddda73d | petehwu/python_practice | /merge_sort.py | 1,315 | 4.1875 | 4 | #!/Users/pwu/anaconda/bin/python3
""" shebang for linux #!/usr/bin/env python3
merge sort algo
"""
def ms(arr):
""" entry point for merge sort
"""
print("before merge sort {}".format(arr))
rms(arr)
print("after merge sort {}".format(arr))
def rms(arr):
""" recursive function that keep splitting the list till 1 element in left and right
"""
mid = len(arr) // 2
if mid > 0:
left = arr[0:mid]
right = arr[mid:]
rms(left)
rms(right)
mergeLR(arr, left, right)
def mergeLR(arr, left, right):
"""merges the left and right into one orderd list
"""
lIdx = 0
rIdx = 0
aIdx = 0
while lIdx < len(left) and rIdx < len(right):
if left[lIdx] < right[rIdx]:
arr[aIdx] = left[lIdx]
lIdx += 1
else:
arr[aIdx] = right[rIdx]
rIdx += 1
aIdx += 1
while lIdx < len(left):
arr[aIdx] = left[lIdx]
lIdx += 1
aIdx += 1
while rIdx < len(right):
arr[aIdx] = right[rIdx]
rIdx += 1
aIdx += 1
if __name__ == '__main__':
ms([20,45,78,23,6,7,2,8,13,77])
print("-----")
ms([1, 2, 3])
print("-----")
ms([1])
print("-----")
ms([1,2])
print("-----")
ms([2, 1])
print("-----")
| false |
7bdd1c6504d419f5f3990d445107d7f7319a1c92 | schaphekar/Graduate-Coursework | /CSC 421 - Applied Algorithms & Structures/sumPossible.py | 1,336 | 4.125 | 4 | ### Given a sorted list, these functions determine if there are elements whose sum adds up to a target value.
import time
# Array initialization
arr1 = [5,2,3,1,4,9,101,333,1,76,555]
arr1 = sorted(arr1)
t1 = 77
t2 = 338
# Function to check if it's possible to get t from two distinct elements
def sumPossible2(arr,target):
i = 0
j = len(arr)-1
while i < j:
if arr[i] + arr[j] == target:
return arr[i], arr[j]
if arr[i] + arr[j] < target:
i += 1
else:
j -= 1
return -1
# Function to check if it's possible to get t from three distinct elements
def sumPossible3(arr,target):
i = 0
j = 1
k = len(arr)-1
while i < k:
while j < k:
if arr[i] + arr[j] + arr[k] == target:
return arr[i], arr[j], arr[k]
if arr[i] + arr[j] + arr[k] < target:
j += 1
else:
k -= 1
i += 1
return -1
# Test results
start_time = time.time();
print(sumPossible2(arr1,t1))
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
print(sumPossible3(arr1,t2))
print("--- %s seconds ---" % (time.time() - start_time))
| true |
6484e434d7bc3f1737ff2989240100364ec72a28 | YarikVznk/Python_cisco | /dne-security-code/intro-python/part1/hands_on_exercise.py | 1,022 | 4.3125 | 4 | """Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
print(pi)
# TODO: Write a conditional to print out if `i` is less than or greater than 50
i = random.randint(0, 100)
if i >= 50:
print(str(i)+"grater than 50")
else:
print(str(i)+"less than 50")
# TODO: Write a conditional that prints the color of the picked fruit
picked_fruit = random.choice(['orange', 'strawberry', 'banana'])
if picked_fruit == 'orange':
print('orange')
elif picked_fruit == 'strawberry':
print('red')
else:
print('yellow')
# TODO: Write a function that multiplies two numbers and returns the result
# Define the function here.
def my_function(a,b):
c = a*b
return c
# TODO: Now call the function a few times to calculate the following answers
print('12 x 96 ={}'.format(my_function(12,96)))
print('48 x 17 ={}'.format(my_function(48,17)))
print("196523 x 87323 =", my_function(196523, 87323))
| true |
a1fee9fc8262ae7dbca206be25c8426f7dfeb21d | kinny94/Stevens-Assignments | /SSW-555 - Agile methods of Software Development/Homework/hw6/hw6.py | 911 | 4.1875 | 4 | import datetime
date1 = datetime.date(2000, 1, 1)
date2 = datetime.date(2016, 10, 3)
def number_of_days_between_two_dates(date_1,date_2):
delta = date2 - date1
print("No of days between " + str(date_1) + " and " + str(date_2) + " are " + str(delta.days))
return int(delta.days)
def number_of_months_between_two_dates(date_1,date_2):
delta = date2 - date1
months = int(delta.days/30.4)
print("No of months between " + str(date_1) + " and " + str(date_2) + " are " + str(months))
return months
def number_of_years_between_two_dates(date_1,date_2):
delta = date2 - date1
years = int(delta.days/365.25)
print ("No of years between " + str(date_1) + " and " + str(date_2) + " are " + str(years))
return years
if __name__ == '__main__':
print(number_of_days_between_two_dates(date1,date2))
print(number_of_months_between_two_dates(date1,date2))
print(number_of_years_between_two_dates(date1,date2)) | false |
df79fdb977f0a4213ab885f2d099011dea11afc1 | mareedez/python-project-lvl1 | /brain_games/games/game_calc.py | 1,229 | 4.125 | 4 | """Brain-calc logic."""
import operator
import random
from brain_games import game_core
OPERATORS = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
}
def question():
"""Generate math problem elements.
Returns:
first_number, second_number: random integers
operation: random operator '-', '+', '*'
"""
first_number = game_core.generate_random_number()
second_number = game_core.generate_random_number()
operation = random.choice(list(OPERATORS.keys()))
return first_number, second_number, operation
def rules():
"""Calc-game rules description.
Returns:
gameplay guidance
"""
return 'What is the result of the expression?\n'
def get_answers():
"""Get answer from user and correct answer.
Returns:
correct_answer: expected answer
user_answer: answer entered by the user
"""
first_number, second_number, operation = question()
correct_answer = str(OPERATORS.get(operation)(first_number, second_number))
quest = 'Question: {0} {1} {2} '
user_answer = input(quest.format(first_number, operation, second_number))
print('Your answer:', user_answer)
return correct_answer, user_answer
| true |
cab656245df0482a8d0405a307db64d6b04d538a | Sridhar-R/Python-basic-programs | /reverse.py | 310 | 4.21875 | 4 | a = raw_input("Enter the string : ")
def reverse(a):
s =""
for i in a:
s = i + s
return s
print reverse(a)
str1 = a
str2 = reverse(a)
print "string 1 is : " , len(str1)
print "string 2 is : ", len(str2)
if str1 == str2:
print str1, " is Palindrome"
else:
print str1, " is not palindrome"
| false |
7608af343d772903379d8f32d3e91481ceb4d090 | cacciella/PythonProEstudos | /Aula_Pro_18b.py | 863 | 4.25 | 4 | # Contagem de Caracteres com Dicionário
def contar_caracteres(s):
""" Função que conta os caracteres de uma string
Ex:
>> contar_caracteres('renzo')
{'e': 1, 'n': 1, 'o': 1, 'r': 1, 'z': 1,}
>> contar_caracteres('banana')
{'a': 3, 'b': 1, 'n': 2}
:param s: string a ser contada
"""
resultado = {}
# resultado mais simplifacado que o anterior
for caracter in s:
resultado[caracter] = resultado.get(caracter, 0) + 1
return resultado
if __name__ == '__main__':
print(contar_caracteres('renzo'))
print()
print(contar_caracteres('banana'))
print()
print()
def contar_carac(s):
result = {}
for caract in s:
result[caract] = result.get(caract, 0) + 1
return result
if __name__ == '__main__':
print(contar_carac('Mauricio'))
print(contar_carac('Maaaaaaaaaaau'))
| false |
b16e0de5064d25676478cdd39bb0897a3cf930d7 | HridoyAlam/learn-python | /code2.py | 350 | 4.15625 | 4 | # Python Program to convert a given list of integers and a tuple of integers into a list of strings
num_list = [1,2,3,4]
num_tuple = (0,1,2,3)
print("Orginal data set")
print(num_list)
print(num_tuple)
result_list = list(map(str,num_list))
result_tuple = list(map(str, num_tuple))
print("After type casting")
print(result_list)
print(result_tuple) | true |
31b055c7913a0463b09eca1931bb4b0e23b2b719 | HridoyAlam/learn-python | /code with mosh/test.py | 1,115 | 4.28125 | 4 | '''
name = input("What's your name? ")
color = input("What's your favorite color? ")
print(name + " likes "+color)
year = input("What's your birth year? ")
age = 2021 - int(year)
print("You are "+ str(age)+ "'s old.")
name = input("Eneter your name: ")
si = len(name)
if 3> si:
print("Name must be at least 3 chracters!")
elif si >= 50:
print("name can't be maximum of 50 character")
else:
print(f'{name} looks good')
wieght = int(input("Enter your Weight: "))
unit = input("(L)lbs or (k) kg: ")
if unit.upper() =='L':
convert = wieght *0.45
print(f'yor are {convert} kilos.')
else:
convert = wieght/0.45
print(f'you are {round(convert,2)} pounds')
'''
'''
i =1;
while i<=5:
#print(i, end=' ')
print('*' * i)
i +=1
'''
secret_number = 9
count = 0
guess_lives = 3
while count < guess_lives:
guess=int(input("guess: "))
count +=1
if guess == secret_number:
print("you won")
break
else:
#lives = guess_lives - count
print(f"you have {guess_lives - count} lives left")
else:
print("Sorry you are failed") | false |
db058daae83820ab726c8ba07a530b5cdfc7fd44 | brajesh-rit/hardcore-programmer | /sliding window/max_subarry.py | 2,607 | 4.34375 | 4 | """
https://www.interviewbit.com/problems/sliding-window-maximum/#
Given an array of integers A. There is a sliding window of size B which
is moving from the very left of the array to the very right.
You can only see the w numbers in the window. Each time the sliding window moves
rightwards by one position. You have to find the maximum for each window.
The following example will give you more clarity.
The array A is [1 3 -1 -3 5 3 6 7], and B is 3.
Window position Max
———————————- ————————-
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Return an array C, where C[i] is the maximum value of from A[i] to A[i+B-1].
Note: If B > length of the array, return 1 element with the max of the array.
"""
class Solution(object):
# Below brute force return maximum limit time is increase error
def maxSlidingWindow1(self, nums, k):
max_val = nums[0]
result = []
for i in range(len(nums) - k + 1): # always add one because last data is missing
max_val =nums[i]
for j in range(i,k+i):
max_val = max(max_val,nums[j])
result.append(max_val)
return result
def maxSlidingWindow(self, nums, k):
start = 0
end = 0
result = []
queue = []
while end < k:
if len(queue) != 0:
i = 0
while i < len(queue):
if queue[i] < nums[end]:
queue.pop(i)
else:
i = i + 1
queue.append(nums[end])
end = end + 1
end = end - 1
result.append(queue[0])
while end < len(nums) - 1:
if queue[0] == nums[start]:
queue.pop(0)
start = start + 1
end = end + 1
if len(queue) != 0:
i = 0
while i < len(queue):
if queue[i] < nums[end]:
queue.pop(i)
else:
i = i + 1
queue.append(nums[end])
result.append(queue[0])
return result
result = Solution()
print (result.maxSlidingWindow( [1,3,1,2,0,5], 3)) #[3,3,2,5] [3,3,1,5]
print (result.maxSlidingWindow( [1,3,-1,-3,5,3,6,7], 3))
print (result.maxSlidingWindow( [1], 1))
print (result.maxSlidingWindow( [1, -1], 1))
print (result.maxSlidingWindow( [9, 11], 2))
print (result.maxSlidingWindow( [4, -2], 2)) | true |
83b714b9519960ff2315a43c156613d0238b5ae4 | brajesh-rit/hardcore-programmer | /Recursion/REC_n_binary_nbr.py | 1,082 | 4.125 | 4 | """
https://practice.geeksforgeeks.org/problems/print-n-bit-binary-numbers-having-more-1s-than-0s0252/1
Print N-bit binary numbers having more 1s than 0s
Given a positive integer N, the task is to find all the N bit binary numbers having more than or equal 1’s than 0’s for
any prefix of the number.
Example 1:
Input: N = 2
Output: 11 10
Explanation: 11 and 10 have more than
or equal 1's than 0's
Example 2:
Input: N = 3
Output: 111 110 101
Explanation: 111, 110 and 101 have more
than or equal 1's than 0's
"""
class Solution:
result = []
def solve (self, nOne, nZero, nTot,out):
if nTot == 0:
self.result.append(out)
return
if nZero < nOne:
op1 = out + '0'
self.solve(nOne,nZero+1,nTot-1, op1)
op2 = out + '1'
self.solve(nOne+1,nZero,nTot-1, op2)
return
def NBitBinary(self, N):
out = '1'
nOne = 1
nZero = 0
N = N - 1
self.solve(nOne,nZero,N,out)
return self.result
N = 5
result = Solution()
print(result.NBitBinary(N)) | true |
565cbeb680af1a0476ae9124c7fd4571653588be | sushmitha0211/Encryption | /encryption.py | 431 | 4.125 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = 3
new_message = ''
message = input('please enter a message:')
for character in message:
if character in alphabet:
position = alphabet.find(character)
new_position = (position + key) % 26
new_character = alphabet[new_position]
new_message += new_character
else:
new_message += character
print("your encrypted message is ", new_message)
| true |
f0c99a185b0e7ee766746d1e0ef57ba67d4b722c | LukaFMF/ProjectEuler | /Problem1/program.py | 422 | 4.125 | 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.
stevilo = 1
vsota = 0
while stevilo < 1000:
if stevilo % 3 == 0 or stevilo % 5 == 0: # ce je stevilo deljivo s 3 ali s 5
vsota += stevilo # ga pristejemo vsoti
stevilo += 1
print(vsota) | false |
607402169c94dad56a8c746bf1721bf493019c96 | twiindan/selenium_lessons | /01_Introducción/03_basic_syntax.py | 2,140 | 4.5625 | 5 |
#===============================================================================
# - One of the basic concepts of programming is a Variable
# - A variable stores a piece of data and give it a specific name
#===============================================================================
spam = 10 # The variable spam now stores the number 10
print (spam)
#===============================================================================
# - Variables can store different data types like booleans, numbers or strings
#===============================================================================
spam = 10 # spam stores the number 10
eggs = True # eggs stores the boolean True
my_variable = 'Python' # my_variable stores the string Python
#===============================================================================
# - The value of variables can be reassigned
#===============================================================================
spam = 10 # spam stores the number 10
print (spam)
spam = 5 # spam stores the number 5
print (spam)
spam = 'Python' # spam stores the string Python
print (spam)
#===============================================================================
# - In Python whitespaces are used to structure code.
# - Python use indentation with four spaces (tab key)
#===============================================================================
spam = 10
print (spam)
def spam():
eggs = 10
return eggs
print(spam())
#===============================================================================
# - Comments can be added to Python code to improve the code understanding
# - A comment is a line of text that Python not run as code, it's just for humans to read.
# - There are two methods to put comments in code depend of comment lenght:
# - Use "#" sign to make a one line comment.
# - Triple quotation marks to make a multi-line comment
#===============================================================================
# Hello I'm a single line comment
"""
Hello I'm a comment
with multiple lines.
"""
| true |
5eff4f8e5c2496ec7e3ef66fbdaeda93b53710ec | brunats/clube-de-python | /ex4_arrays_strings_listas_dicts.py | 963 | 4.28125 | 4 | ## Lista exercicios arrays, strings, listas e dicts
## Exercicio 1
# Crie duas strings e apresente o tamanho de cada uma;
## ->
frutas = ['Banana', 'Melancia', 'Limao']
cidades = ['Joinville', 'Araquari']
print('Frutas: ', frutas)
print('Cidades: ', cidades)
print('Tamanho da lista de frutas: ', len(frutas))
print('Tamanho da lista de cidades: ', len(cidades))
## <-
## Exercicio 2
# Crie uma lista com no mínimo 2 elementos, e atribua as funções insert() e remove();
## ->
frutas = ['Banana', 'Melancia', 'Limao']
print('Frutas: ', frutas)
frutas.insert(1, 'Kiwi')
print('Frutas: ', frutas)
frutas.remove('Limao')
print('Frutas: ', frutas)
## <-
## Exercicio 3
# Crie outra lista, e as compare.
## ->
frutas = ['Banana', 'Melancia', 'Limao']
carros = ['Sentra', 'Gol', 'Civic', 'Fluence']
print('Lista de frutas: ', frutas)
print('Lista de carros: ', carros)
print('Lista de frutas eh maior que a de carros? ', frutas > carros)
## <-
| false |
2e3c662f3d706576d7a77a7da6457fc7324d0698 | cmdellinger/exercism.io | /python/robot-simulator/robot_simulator.py | 1,989 | 4.28125 | 4 | """
Exercism.io assignment: robot_simulator.py
written by (GitHub): cmdellinger
Python version: 2.7
Implementation of Robot class that moves a robot along coordinates according to
a string of directions.
See README file for more detailed information.
"""
# Globals for the bearings
# Change the values as you see fit
EAST = (1,0)
NORTH = (0,1)
WEST = (-1,0)
SOUTH = (0,-1)
class Robot(object):
''' Robot class:
functionality outlined in README
'''
BEARINGS = [NORTH, EAST, SOUTH, WEST]
''' list: bearings in compass order
store bearings in compass order, so robot rotations can progress up and
down the list.
'''
def __init__(self, bearing=NORTH, x=0, y=0):
self.coordinates = (x,y)
self.bearing = bearing
def change_bearing(self, rotations = 0):
''' parent function for direction turns.
rotates robot clockwise (+) and counterclockwise (-).
'''
current = self.BEARINGS.index(self.bearing)
self.bearing = self.BEARINGS[(current + rotations) % 4]
''' modulus of calculated bearing accounts for index > 3.
Python's negative index behavior allows for automatic wrap around.
'''
def turn_right(self, turns = 1):
''' rotates robot right or clockwise '''
self.change_bearing(turns)
def turn_left(self, turns = 1):
''' rotates robot left or counterclockwise '''
self.change_bearing(-turns)
def advance(self):
''' progresses robot in direction of bearing '''
self.coordinates = tuple(x+y for x,y in zip(self.coordinates, self.bearing))
def simulate(self, operations = ''):
''' translates string of instructions into movements '''
instructions = {'R': self.turn_right,
'L': self.turn_left,
'A': self.advance}
for operation in operations:
instructions[operation]()
| true |
c3167d0f971d1f30d57d4082caceb0d1011d56b1 | cmdellinger/exercism.io | /python/atbash-cipher/atbash_cipher.py | 1,861 | 4.125 | 4 | """
Exercism.io assignment: atbash_cipher.py
written by (GitHub): cmdellinger
Python version: 2.7
Usage:
atbash_cipher.py --dec <"string">
atbash_cipher.py --enc <"string">
Options:
--enc,-e flag to encode
--dec,-d flag to decode
Applies the atbash cipher to the given string. The atbash cipher reverses the
alphabet character, so 'a'-'z' becomes the corresponding 'z'-'a'.
Any non-alphanumeric will be stripped and encoded text will be output in blocks
of 5 character (as specified in problem's README file).
"""
## ------
## Exercism.io solution
## ------
def codec(text):
''' core cipher function to strip and encode/decode text '''
from string import ascii_lowercase as alphabet
def cipher(char = ''):
''' helper function to change only alpha characters '''
if char.isalpha():
# find index in alphabet string, then return opposite (~)
return alphabet[~alphabet.index(char)]
else: return char
# strip string to letters and numbers, make lowercase, apply cipher, & join
return ''.join(cipher(char) for char in filter(str.isalnum, text.lower()))
def encode(plain_text = ''):
''' strips string to letter/numbers and encodes using atbash cipher '''
from re import findall
# use regex to pull blocks of 5 characters and join returned list
return ' '.join(findall('.{1,5}', codec(plain_text)))
def decode(ciphered_text = ''):
''' strips string to letter/numbers and decodes using atbash cipher '''
return codec(ciphered_text)
## ------
## Command-line implementation
## ------
if __name__ == '__main__':
from docopt import docopt
text = docopt(__doc__)['<"string">']
if docopt(__doc__)['--enc']: print encode(text)
elif docopt(__doc__)['--dec']: print decode(text)
else: print __doc__
| true |
b6e22ab76036bb38b084b9a4e0cae177f616d464 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Introduction_to_Linear_Modeling_in_Python/1.1.3.Reasons_for_Modeling:Estimating_Relationships.py | 2,030 | 4.6875 | 5 | '''Another common application of modeling is to compare two data sets by building models for each, and then comparing the models. In this exercise, you are given data for a road trip two cars took together. The cars stopped for gas every 50 miles, but each car did not need to fill up the same amount, because the cars do not have the same fuel efficiency (MPG). Complete the function efficiency_model(miles, gallons) to estimate efficiency as average miles traveled per gallons of fuel consumed. Use the provided dictionaries car1 and car2, which both have keys car['miles'] and car['gallons'].'''
#TASK
# Complete the function definition for efficiency_model(miles, gallons)
# Use the function to compute the efficiency of the provided cars (dicts car1, car2)
# Store your answers as car1['mpg'] and car2['mpg'].
# Indicate which car has the best mpg by setting best_car=1, best_car=2, or best_car=0 if the same.
# Complete the function to model the efficiency.
def efficiency_model(miles, gallons):
return np.mean( ____ / ____ )
# Use the function to estimate the efficiency for each car.
car1['mpg'] = efficiency_model( car1['____'] , car1['____'] )
car2['mpg'] = efficiency_model( car2['____'] , car2['____'] )
# Finish the logic statement to compare the car efficiencies.
if car1['mpg'] ____ car2['mpg'] :
print('car1 is the best')
elif car1['mpg'] ____ car2['mpg'] :
print('car2 is the best')
else:
print('the cars have the same efficiency')
#SOLUTION
# Complete the function to model the efficiency.
def efficiency_model(miles, gallons):
return np.mean(miles/gallons)
# Use the function to estimate the efficiency for each car.
car1['mpg'] = efficiency_model(car1['miles'], car1['gallons'])
car2['mpg'] = efficiency_model(car2['miles'], car2['gallons'])
# Finish the logic statement to compare the car efficiencies.
if car1['mpg'] > car2['mpg'] :
print('car1 is the best')
elif car1['mpg'] < car2['mpg'] :
print('car2 is the best')
else:
print('the cars have the same efficiency') | true |
efad38693739d73f855855dd626e5d8aabbb8961 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Machine_Learning/2.Unsupervised_Learning_in_Python/1.3.1.Scaling_fish_data_for_clustering.py | 1,574 | 4.125 | 4 | '''You are given an array samples giving measurements of fish. Each row represents an individual fish.
The measurements, such as weight in grams, length in centimeters, and the percentage ratio of height to length, have very different scales.
In order to cluster this data effectively, you'll need to standardize these features first. In this exercise, you'll build a pipeline to standardize and cluster the data.
These fish measurement data were sourced from the Journal of Statistics Education.- http://ww2.amstat.org/publications/jse/jse_data_archive.htm'''
# #TASK
# Import:
# make_pipeline from sklearn.pipeline.
# StandardScaler from sklearn.preprocessing.
# KMeans from sklearn.cluster.
# Create an instance of StandardScaler called scaler.
# Create an instance of KMeans with 4 clusters called kmeans.
# Create a pipeline called pipeline that chains scaler and kmeans. To do this, you just need to pass them in as arguments to make_pipeline().
# Perform the necessary imports
from ____ import ____
from ____ import ____
from ____ import ____
# Create scaler: scaler
scaler = ____
# Create KMeans instance: kmeans
kmeans = ____
# Create pipeline: pipeline
pipeline = ____
#SOLUTION
# Perform the necessary imports
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
# Create scaler: scaler
scaler = StandardScaler()
# Create KMeans instance: kmeans
kmeans = KMeans(n_clusters=4)
# Create pipeline: pipeline
pipeline = make_pipeline(scaler, kmeans)
print(pipeline)
| true |
80d7149d1371c80997ffeaabe554cba91b6ec1b1 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Building_Chatbots_in_Python/3.2.1.Creating_queries_from_parameters.py | 1,775 | 4.34375 | 4 | '''Now you're going to implement a more powerful function for querying the hotels database.
The goal is to take arguments that can later be specified by other parts of your code.
Specifically, your job here is to define a find_hotels() function which takes a single argument - a dictionary of column names and values - and returns a list of matching hotels from the database.'''
#TASK
# Initialise a query string containing everything before the "WHERE" keyword.
# A filters list has been created for you. Join this list together with the strings " WHERE " and " and ".
# Create a tuple of the values of the params dictionary.
# Create a connection and cursor to "hotels.db" and then execute the query, just as in the previous exercise.
# Define find_hotels()
def find_hotels(params):
# Create the base query
query = 'SELECT * FROM hotels'
# Add filter clauses for each of the parameters
if len(params) > 0:
filters = ["{}=?".format(k) for k in params]
query += " ____ " + " ____ ".join(____)
# Create the tuple of values
t = tuple(____)
# Open connection to DB
conn = sqlite3.connect("____")
# Create a cursor
c = ____
# Execute the query
____
# Return the results
____
#SOLUTION
# Define find_hotels()
def find_hotels(params):
# Create the base query
query = 'SELECT * FROM hotels'
# Add filter clauses for each of the parameters
if len(params) > 0:
filters = ["{}=?".format(k) for k in params]
query += " ____ " + " ____ ".join(____)
# Create the tuple of values
t = tuple(____)
# Open connection to DB
conn = sqlite3.connect("____")
# Create a cursor
c = ____
# Execute the query
____
# Return the results
____
| true |
2e36078f985199332b4578a65483376fa05f8273 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Introduction_to_Linear_Modeling_in_Python/3.1.1.Linear_Model_in_Anthropology.py | 2,085 | 4.53125 | 5 | '''If you found part of a skeleton, from an adult human that lived thousands of years ago, how could you estimate the height of the person that it came from? This exercise is in part inspired by the work of forensic anthropologist Mildred Trotter, who built a regression model for the calculation of stature estimates from human "long bones" or femurs that is commonly used today.
In this exercise, you'll use data from many living people, and the python library scikit-learn, to build a linear model relating the length of the femur (thigh bone) to the "stature" (overall height) of the person. Then, you'll apply your model to make a prediction about the height of your ancient ancestor.'''
#TASK
# import LinearRegression from sklearn.linear_model and initialize the model with fit_intercept=False
# Reshape the pre-loaded data arrays legs and heights, from "1-by-N" to "N-by-1" arrays.
# Pass the reshaped arrays legs and heights into model.fit().
# use model.predict() to predict the value fossil_height for the newly found fossil fossil_leg = 50.7.
# import the sklearn class LinearRegression and initialize the model
from sklearn.____ import ____
model = LinearRegression(fit_intercept=False)
# Prepare the measured data arrays and fit the model to them
legs = legs.reshape(len(____),1)
heights = heights.reshape(len(____),1)
model.fit(____, heights)
# Use the fitted model to make a prediction for the found femur
fossil_leg = 50.7
fossil_height = model.predict(____)
print("Predicted fossil height = {:0.2f} cm".format(fossil_height[0,0]))
#SOLUTION
# import the sklearn class LinearRegression and initialize the model
from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=False)
# Prepare the measured data arrays and fit the model to them
legs = legs.reshape(len(legs),1)
heights = heights.reshape(len(heights),1)
model.fit(legs, heights)
# Use the fitted model to make a prediction for the found femur
fossil_leg = 50.7
fossil_height = model.predict(fossil_leg)
print("Predicted fossil height = {:0.2f} cm".format(fossil_height[0,0])) | true |
465a962cafbeebb619256b704ae3ad31ea19775d | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Natural_Language_Processing_Fundamentals/1.3.2.Non-ascii_tokenization.py | 1,837 | 4.625 | 5 | '''In this exercise, you'll practice advanced tokenization by tokenizing some non-ascii based text.
You'll be using German with emoji!
Here, you have access to a string called german_text, which has been printed for you in the Shell.
Notice the emoji and the German characters!
The following modules have been pre-imported from nltk.tokenize: regexp_tokenize and word_tokenize.
Unicode ranges for emoji are:
('\U0001F300'-'\U0001F5FF'),
('\U0001F600-\U0001F64F'),
('\U0001F680-\U0001F6FF'), and
('\u2600'-\u26FF-\u2700-\u27BF').'''
#TASK
# Tokenize all the words in german_text using word_tokenize(), and print the result.
# Tokenize only the capital words in german_text.
# First, write a pattern called capital_words to match only capital words. Make sure to check for the German Ü!
# Then, tokenize it using regexp_tokenize().
# Tokenize only the emoji in german_text. The pattern using the unicode ranges for emoji given in the assignment text has been written for you. Your job is to use regexp_tokenize() to tokenize the emoji.
# Tokenize and print all words in german_text
all_words = ____(____)
print(all_words)
# Tokenize and print only capital words
capital_words = r"[____]\w+"
print(____(____, ____))
# Tokenize and print only emoji
emoji = "['\U0001F300-\U0001F5FF'|'\U0001F600-\U0001F64F'|'\U0001F680-\U0001F6FF'|'\u2600-\u26FF\u2700-\u27BF']"
print(____(____, ____))
#SOLUTION
# Tokenize and print all words in german_text
all_words = word_tokenize(german_text)
print(all_words)
# Tokenize and print only capital words
capital_words = r"[A-ZÜ]\w+"
print(regexp_tokenize(german_text, capital_words))
# Tokenize and print only emoji
emoji = "['\U0001F300-\U0001F5FF'|'\U0001F600-\U0001F64F'|'\U0001F680-\U0001F6FF'|'\u2600-\u26FF\u2700-\u27BF']"
print(regexp_tokenize(german_text, emoji))
| true |
96c77d75c3d6c75ec051d9ee3ba498c376963c41 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Foundations_of_Predictive_Analytics_in_Python(Part 1)/3.5.Business_case_using_lift_curve.py | 2,282 | 4.1875 | 4 | '''In the video you learned to implement a method that calculates the profit of a campaign:
profit = profit(perc_targets, perc_selected, population_size, campaign_cost, campaign_reward)
In this method, perc_targets is the percentage of targets in the group that you select for your campaign,
perc_selected the percentage of people that is selected for the campaign, population_size the total population size,
campaign_cost the cost of addressing a single person for the campaign, and campaign_reward the reward of addressing a target.
In this exercise you will learn for a specific case whether it is useful to use a model,
by comparing the profit that is made when addressing all donors versus the top 40% of the donors.'''
#TASK
# Plot the lift curve. The predictions are in predictions_test and the true target values are in targets_test.
# Read the lift value at 40% and fill it out.
# The information about the campaign is filled out in the script. Calculate the profit made when addressing the entire population.
# Calculate the profit made when addressing the top 40%.
# Plot the lift graph
skplt.metrics.plot_lift_curve(____, ____)
plt.show()
# Read the lift at 40% (round it up to the upper tenth)
perc_selected = 0.4
lift = ____
# Information about the campaign
population_size, target_incidence, campaign_cost, campaign_reward = 100000, 0.01, 1, 100
# Profit if all donors are targeted
profit_all = profit(____, 1, population_size, campaign_cost, campaign_reward)
print(profit_all)
# Profit if top 40% of donors are targeted
profit_40 = profit(____ * ____, 0.4, population_size, campaign_cost, campaign_reward)
print(profit_40)
#SOLUTION
# Plot the lift graph
skplt.metrics.plot_lift_curve(targets_test, predictions_test)
plt.show()
# Read the lift at 40% (round it up to the upper tenth)
perc_selected = 0.4
lift = 1.5
# Information about the campaign
population_size, target_incidence, campaign_cost, campaign_reward = 100000, 0.01, 1, 100
# Profit if all donors are targeted
profit_all = profit(target_incidence, 1, population_size, campaign_cost, campaign_reward)
print(profit_all)
# Profit if top 40% of donors are targeted
profit_40 = profit(lift * target_incidence, 0.4, population_size, campaign_cost, campaign_reward)
print(profit_40) | true |
2d0d32ec2f82ad5926ff40fdc3dad7537fc2ceb5 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Foundations_of_Predictive_Analytics_in_Python(Part 1)/4.9.Plotting_the_group_sizes.py | 1,992 | 4.40625 | 4 | '''The predictor insight graph gives information about predictive variables.
Each variable divides the population in several groups.
The predictor insight graph has a line that shows the average target incidence for each group, and a bar that shows the group sizes.
In this exercise, you will learn how to write and apply a function that plots a predictor insight graph, given a predictor insight graph table.'''
#TASK
# Plot the bars that show the Size of each group.
# Plot the incidence line that shows the average target incidence of each group.
# The function to plot a predictor insight graph
def plot_pig(pig_table,variable):
# Plot formatting
plt.ylabel("Size", rotation = 0,rotation_mode="anchor", ha = "right" )
# Plot the bars with sizes
pig_table["____"].plot(kind="bar", width = 0.5, color = "lightgray", edgecolor = "none")
# Plot the incidence line on secondary axis
pig_table["____"].plot(secondary_y = True)
# Plot formatting
plt.xticks(np.arange(len(pig_table)), pig_table[variable])
plt.xlim([-0.5, len(pig_table)-0.5])
plt.ylabel("Incidence", rotation = 0, rotation_mode="anchor", ha = "left")
# Show the graph
plt.show()
#SOLUTION
# The function to plot a predictor insight graph
def plot_pig(pig_table,variable):
# Plot formatting
plt.ylabel("Size", rotation = 0,rotation_mode="anchor", ha = "right" )
# Plot the bars with sizes
pig_table["Size"].plot(kind="bar", width = 0.5, color = "lightgray", edgecolor = "none")
# Plot the incidence line on secondary axis
pig_table["Incidence"].plot(secondary_y = True)
# Plot formatting
plt.xticks(np.arange(len(pig_table)), pig_table[variable])
plt.xlim([-0.5, len(pig_table)-0.5])
plt.ylabel("Incidence", rotation = 0, rotation_mode="anchor", ha = "left")
# Show the graph
plt.show()
# Apply the function for the variable "country"
plot_pig(pig_table, "country") | true |
ab77fb170707308227f13c6e57196c253aea4df4 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Introduction_to_Linear_Modeling_in_Python/4.3.1.Bootstrap_and_Standard_Error.py | 2,543 | 4.21875 | 4 | '''Imagine a National Park where park rangers hike each day as part of maintaining the park trails. They don't always take the same path, but they do record their final distance and time. We'd like to build a statistical model of the variations in daily distance traveled from a limited sample of data from one ranger.
Your goal is to use bootstrap resampling, computing one mean for each resample, to create a distribution of means, and then compute standard error as a way to quantify the "uncertainty" in the sample statistic as an estimator for the population statistic.
Use the preloaded sample_data array of 500 independent measurements of distance traveled. For now, we this is a simulated data set to simplify this lesson. Later, we'll see more realistic data.'''
#TASK
# Assign the sample_data as the model for the population.
# Iterate num_resamples times, using np.random.choice() each time to generate a bootstrap_sample of size=resample_size taken from the population_model, with replacement=True, and compute and store the sample mean each time.
# Compute and print the np.mean() and np.std() of bootstrap_means.
# Use the predefined plot_data_hist() and visualize the bootstrap_means distribution.
# Use the sample_data as a model for the population
population_model = ____
# Resample the population_model 100 times, computing the mean each sample
for nr in range(num_resamples):
bootstrap_sample = np.random.____(population_model, size=____, replace=____)
bootstrap_means[nr] = np.____(bootstrap_sample)
# Compute and print the mean, stdev of the resample distribution of means
distribution_mean = np.mean(____)
standard_error = np.std(____)
print('Bootstrap Distribution: center={:0.1f}, spread={:0.1f}'.format(____, ____))
# Plot the bootstrap resample distribution of means
fig = plot_data_hist(____)
#SOLUTION
# Use the sample_data as a model for the population
population_model = sample_data
# Resample the population_model 100 times, computing the mean each sample
for nr in range(num_resamples):
bootstrap_sample = np.random.choice(population_model, size=resample_size, replace=True)
bootstrap_means[nr] = np.mean(bootstrap_sample)
# Compute and print the mean, stdev of the resample distribution of means
distribution_mean = np.mean(bootstrap_means)
standard_error = np.std(bootstrap_means)
print('Bootstrap Distribution: center={:0.1f}, spread={:0.1f}'.format(distribution_mean, standard_error))
# Plot the bootstrap resample distribution of means
fig = plot_data_hist(bootstrap_means) | true |
55b3b60d0511431b755cb1e5706d05672766e47a | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Introduction_to_Linear_Modeling_in_Python/4.1.2.Variation_in_Sample_Statistics.py | 2,372 | 4.53125 | 5 | '''If we create one sample of size=1000 by drawing that many points from a population. Then compute a sample statistic, such as the mean, a single value that summarizes the sample itself.
If you repeat that sampling process num_samples=100 times, you get 100 samples. Computing the sample statistic, like the mean, for each of the different samples, will result in a distribution of values of the mean. The goal then is to compute the mean of the means and standard deviation of the means.
Here you will use the preloaded population, num_samples, and num_pts, and note that the means and deviations arrays have been initialized to zero to give you containers to use for the for loop.'''
#TASK
# For each of num_samples=100, generate a sample, then compute and storing the sample statistics.
# For each iteration, create a sample by using np.random.choice() to draw 1000 random points from the population.
# For each iteration, compute and store the methods sample.mean() and sample.std() to compute the mean and standard deviation of the sample.
# For the array of means and the array of deviations, compute both the mean and standard deviation of each, and print the results.
# Initialize two arrays of zeros to be used as containers
means = np.zeros(num_samples)
stdevs = np.zeros(num_samples)
# For each iteration, compute and store the sample mean and sample stdev
for ns in range(num_samples):
sample = np.____.choice(population, num_pts)
means[ns] = sample.____()
stdevs[ns] = sample.____()
# Compute and print the mean() and std() for the sample statistic distributions
print("Means: center={:>6.2f}, spread={:>6.2f}".format(means.mean(), means.std()))
print("Stdevs: center={:>6.2f}, spread={:>6.2f}".format(stdevs.____(), stdevs.____()))
#SOLUTION
# Initialize two arrays of zeros to be used as containers
means = np.zeros(num_samples)
stdevs = np.zeros(num_samples)
# For each iteration, compute and store the sample mean and sample stdev
for ns in range(num_samples):
sample = np.random.choice(population, num_pts)
means[ns] = sample.mean()
stdevs[ns] = sample.std()
# Compute and print the mean() and std() for the sample statistic distributions
print("Means: center={:>6.2f}, spread={:>6.2f}".format(means.mean(), means.std()))
print("Stdevs: center={:>6.2f}, spread={:>6.2f}".format(stdevs.mean(), stdevs.std()))
| true |
4d3b0b3c4f25c77c18c7dc68c26e24ab23f25a28 | ContangoRango/Machine_Learning_AI_Blockchain | /DataCamp_Introduction_to_Linear_Modeling_in_Python/4.1.3.Visualizing_Variation_of_a_Statistic.py | 1,765 | 4.28125 | 4 | '''Previously, you have computed the variation of sample statistics. Now you'll visualize that variation.
We'll start with a preloaded population and a predefined function get_sample_statistics() to draw the samples, and return the sample statistics arrays.
Here we will use a predefined plot_hist() function that wraps the matplotlib method axis.hist(), which both bins and plots the array passed in. In this way you can see how the sample statistics have a distribution of values, not just a single value.'''
#TASK
# Pass the population into get_sample_statistics() to get the sample statistic distributions.
# Use np.linspace() to define histogram bin edges for each statistic array.
# Use the predefined plot_hist() twice, to plot the statistic distributions means and deviations as two separate histograms.
# Generate sample distribution and associated statistics
means, stdevs = get_sample_statistics(____, num_samples=100, num_pts=1000)
# Define the binning for the histograms
mean_bins = np.____(97.5, 102.5, 51)
std_bins = np.____(7.5, 12.5, 51)
# Plot the distribution of means, and the distribution of stdevs
fig = plot_hist(data=____, bins=____, data_name="Means", color='green')
fig = plot_hist(data=____, bins=____, data_name="Stdevs", color='red')
#SOLUTION
# Generate sample distribution and associated statistics
means, stdevs = get_sample_statistics(population, num_samples=100, num_pts=1000)
# Define the binning for the histograms
mean_bins = np.linspace(97.5, 102.5, 51)
std_bins = np.linspace(7.5, 12.5, 51)
# Plot the distribution of means, and the distribution of stdevs
fig = plot_hist(data=means, bins=mean_bins, data_name="Means", color='green')
fig = plot_hist(data=stdevs, bins=std_bins, data_name="Stdevs", color='red') | true |
72a976888eec9e723d3884010a49cfa39a766954 | tiendong96/Python | /Practice/String/sWAP_cASE.py | 459 | 4.34375 | 4 | #You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
def swap_case(s):
#return s.swapcase() inbuilt Libraries
result = ""
for letter in s:
if letter.isupper():
result += letter.lower()
else:
result += letter.upper()
return result
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result) | true |
1aeb241c31fabcc55b66ffb5367cedbc16d085fc | tiendong96/Python | /PythonPractice/Functions/keywordArguments.py | 443 | 4.125 | 4 | def increment(number,by):
return number + by
#in this case you won't need to result variable
#result = increment(2, 1)
print(increment(2,1)) #python will temporarily store the value in a variable created by python interpreter
#if youre working with a lot of arguments and it's not quite clear what the arguments are for
#you can assign the arguments by the parameter name
#this is called keyword arguments
print(increment(number=2,by=1)) | true |
a9545b4d9feb2dab46de8c5794927ff3febb3679 | tiendong96/Python | /PythonPractice/Lists/twoDimensionalLists.py | 309 | 4.28125 | 4 | matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print(matrix[0][2]) #prints 3
#can rewrite values too
matrix[0][2] = 20
print(matrix)
print()
#can print pretty arrays with numpy
import numpy as np
print(np.matrix(matrix))
#iterating matrices
for row in matrix:
for item in row:
print(item) | true |
a8d3f9b43c2bffdf683e2fcaa3862ababa2e1186 | andradejunior/cracking-the-code | /Python/I. Data Structures/Chapter 3 | Stacks and Queues/3.5 Sort Stack.py | 1,224 | 4.25 | 4 | """
3.5 Sort Stack.
Write a program to sort a stack such that the smallest items are on the top.
You can use an additional temporary stack, but you may not copy the elements
into any other data structure(such as an array). The stack supports the
following operations: push, pop, peek, and isEmpty.
"""
class Stack(list):
"""Stack class using a python list."""
def __init__(self):
"""Init method."""
super()
def is_empty(self):
"""Check if stack is empty."""
return not self
def peek(self):
"""Method to return the top of the stack."""
return self[-1] if len(self) else None
def pop(self):
"""Method to remove the top item from the stack."""
return super().pop()
def push(self, item):
"""Method to add an item to the top of the stack."""
super().append(item)
def sort_stack(stack):
"""Method to sort a stack."""
sorted_stack = Stack()
sorted_stack.push(stack.pop())
while not stack.is_empty():
temp = stack.pop()
while not sorted_stack.is_empty() and temp > sorted_stack.peek():
stack.push(sorted_stack.pop())
sorted_stack.push(temp)
return sorted_stack
| true |
d902de2bb8a61473166f20df696e0b3ac430730c | andradejunior/cracking-the-code | /Python/I. Data Structures/Chapter 1 | Arrays and Strings/1.3 URLify.py | 856 | 4.5 | 4 | """
1.3 URLify.
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.
(Note: If implementing in Java, please use a character array so that you can
perform this operation in place)
EXAMPLE
Input: "Mr John Smith ", 13
Output: "Mr%20John%20Smith"
"""
def urlify(s):
"""
Method to replace all spaces in a string with '%20'.
We can split the string into a list and join the words puting the
character '%20' between each word. Complexity is O(n). A less
pythonic way is do that within a for loop instead of use the method
join.
Args:
s: input string.
Return:
output: string with the spaces replaced by '%20'.
"""
return '%20'.join(s.split())
| true |
70f56a795434b7dff38f3f41e547c2e6f1544892 | andradejunior/cracking-the-code | /Python/I. Data Structures/Chapter 3 | Stacks and Queues/3.1 Three in One.py | 1,706 | 4.34375 | 4 | """
3.1 Three in One.
Describe how you could use a single array to implement three stacks.
"""
class FixedMultiStack:
"""Class for a Fixed Multi Stack."""
def __init__(self, stack_size):
"""Init method."""
self.num_stacks = 3
self.array = [0] * (stack_size * self.num_stacks)
self.sizes = [0] * self.num_stacks
self.stack_size = stack_size
def push(self, item, stack_num):
"""Method to add an item to the top of the stack."""
if self.is_full(stack_num):
raise Exception('Stack is full.')
self.sizes[stack_num] += 1
self.array[self.index_of_top(stack_num)] = item
def pop(self, stack_num):
"""Method to remove the top item from the stack."""
if self.is_empty(stack_num):
raise Exception('Stack is empty.')
value = self.array[self.index_of_top(stack_num)]
self.array[self.index_of_top(stack_num)] = 0
self.sizes[stack_num] -= 1
return value
def peek(self, stack_num):
"""Method to return the top of the stack."""
if self.is_empty(stack_num):
raise Exception('Stack is empty.')
return self.array[self.index_of_top(stack_num)]
def is_empty(self, stack_num):
"""Method to check if the stack is empty."""
return self.sizes[stack_num] == 0
def is_full(self, stack_num):
"""Method to verify if the stack is full."""
return self.sizes[stack_num] == self.stack_size
def index_of_top(self, stack_num):
"""Method to return the index of the top of the stack."""
offset = stack_num * self.stack_size
return offset + self.sizes[stack_num] - 1
| true |
94b8c388c837d60d19d24b385c7ea7a069f824d4 | JestVA/square-numbers | /solution-c-python.py | 754 | 4.28125 | 4 | # Program that lists the first 20 square numbers
#for i in range(1, 21):
# i = i * i
# print(i)
#Updated version that asks for command line attribute and prints out a value, with defensive programming for errors such as type string, int or outside of bound.
squareNumbers = (input("Chose a number between 1 and 20: "))
if str.isdigit(squareNumbers):
if int(squareNumbers) < 21 and int(squareNumbers) > 0:
for squareNumbers in range(1, int(squareNumbers)+1):
squareNumbers = squareNumbers * squareNumbers
print(squareNumbers)
else:
print("You chose a number that is outside the range")
else:
print("Nice try, but either you did not type a number or the number is not in the 1 to 20 range")
| true |
065912ca093c57d0592fe07efdff344e6cb9976e | shalinie22/guvi | /codekata/absolute_beginner/length_of_its_circumference.py | 370 | 4.375 | 4 | #Find the length of its circumference.
#define the function for circumference
def circumference(r):
#formula for circumference
c=2*22/7*r
return c
#get the radius from the user
r=float(input())
#condition to check the radius from the user
if(r<0):
print("Error")
#else calculate the circumference
else:
v=circumference(r)
l=round(v,2)
print(l,end="")
| true |
8db24a01cc331e2ea0e3f5308b4d466ddccb3a71 | shalinie22/guvi | /codekata/absolute_beginner/smaller_number.py | 301 | 4.125 | 4 | # Find and print the smaller number.
#define the function to find the smallest no
def smallest (x,y):
#condition to find the smallest no
if(x<y):
return x
else:
return y
#get the input from the user
x, y = input().split()
#call the function smallest
s=smallest(x,y)
print(s)
| true |
8877826ac89ebcb95d2a9b651528cf0fb046e527 | shalinie22/guvi | /codekata/input&output/line_by_line_inputs.py | 328 | 4.40625 | 4 |
"""
Write a code to get the input in the given format and print the output in the given format
Input Description:
Three integers are given in line by line.
Output Description:
Print the integers in a single line separate by space.
Sample Input :
2
4
5
Sample Output :
2 4 5
"""
x=input()
y=input()
z=input()
print(x,y,z)
| true |
43c09bbf73ca181955c370f0b53fbfab98c0850b | shalinie22/guvi | /codekata/absolute_beginner/length_of_the_string.py | 373 | 4.15625 | 4 | # Remove all the whitespaces and find it's length
#define the function to remone the white space fro the string
def remove_space(a):
#use the replace function to remove the whitespaces
return a.replace(" ","")
#get the string from the user
a=input("")
#call the function remove_space
s=remove_space(a)
#print the output by using the len function
print(len(s),end="")
| true |
d572b41889f58de959606361a6922eff1355fd8e | shalinie22/guvi | /codekata/input&output/string separated by line.py | 331 | 4.25 | 4 |
"""
Write a code to get the input in the given format and print the output in the given format.
Input Description:
A single line contains a string.
Output Description:
Print the characters in a string separated by line.
Sample Input :
guvigeek
Sample Output :
g
u
v
i
g
e
e
k
"""
a=input()
w=list(a)
for i in w:
print(i)
| true |
4cc76e6c7675172b6643783e51e3f4ec1bb02713 | shalinie22/guvi | /codekata/absolute_beginner/leap_year_or_not .py | 333 | 4.1875 | 4 | #to check whether this year is a leap year or not.
#define a function for leap year
def leap_year(y):
#condition to check leap year or not
if(y%4==0):
#if yes return y
return 'Y'
else:
#if NO return N
return 'N'
#get the year from the user
y=int(input())
#call the function leap_year
o=leap_year(y)
print(o)
| true |
32851e8f917d6d222a57f56d8c3e8086d4d7c527 | hariharanragothaman/pingPong | /paddle.py | 1,411 | 4.28125 | 4 | import pygame
BLACK = (0, 0, 0)
"""
Consider a sprite as an object.
An object can have different properties (e.g. width, height, colour, etc.) and methods
(e.g. jump(), hide(), moveForward(), etc.).
Like in the industry an object is built from a mould.
In computing the mould is called a Class.
"""
# class Paddle imports the Sprite class - So any real world objects have to import them
class Paddle(pygame.sprite.Sprite):
def __init__(self, color, width, height):
super().__init__() # call the parent class constructor
# Pass in the color of the paddle, and its x and y position, width and height.
# Set the background color and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(BLACK)
self.image.set_colorkey(BLACK)
# Draw the paddle (a rectangle!)
pygame.draw.rect(self.image, color, [0, 0, width, height])
# Fetch the rectangle object that has the dimensions of the image.
self.rect = self.image.get_rect()
def moveUp(self, pixels):
self.rect.y -= pixels
# Check that you are not going too far (off the screen)
if self.rect.y < 0:
self.rect.y = 0
def moveDown(self, pixels):
self.rect.y += pixels
# Check that you are not going too far (off the screen)
if self.rect.y > 400:
self.rect.y = 400
| true |
b7c7707a558c012669f2b5093804a13403385cee | Barracudakun/CareeristHW13 | /Class13_HW1.py | 609 | 4.46875 | 4 | #1. Reverse a Statement
# Build an algorithm that will print the given statement in reverse.
# Example: Initial string = Everything is hard before it is easy
# Reversed string = easy is it before hard is Everything
def rev_sentence(sentence):
# first split the string into words
words = sentence.split(' ')
# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))
# finally return the joined string
return reverse_sentence
if __name__ == "__main__":
input = 'everything is hard before it is easy'
print(rev_sentence(input))
| true |
40e9aae42fdb6583e1447874f3abbe88dee84f3f | silasechegini/My_Projects | /Quick_sort.py | 1,627 | 4.40625 | 4 | #the quick sort algorithm is one of the efficient sorting algorithms after
#the merge sort. Its efficiency is seen in much larger data sets.
#defines the main operations of the quick sort algorithm
def quick_sort(dataset, head, tail):
if head < tail:
# function call to calculate the split point
pivot_Index = partition(dataset, head, tail)
# now sort the two partitions
quick_sort(dataset, head, pivot_Index-1)
quick_sort(dataset, pivot_Index+1, tail)
#calculate the split point and return the value
def partition(data, head, tail):
pivot = data[head]
L_index = head + 1
U_index = tail
done = False
# keep moving the upper and lower indicies,
# swap the uppen and lower index value when lower > pivot
# and upper < pivot; do until the split point is found.
while not done:
while (L_index <= U_index) and (data[L_index] <= pivot):
L_index += 1
while (U_index >= L_index) and (data[U_index]>= pivot):
U_index -= 1
if L_index > U_index:
done = True
else:
temp = data[L_index]
data[L_index] = data[U_index]
data[U_index] = temp
#Swap the pivot value and the upper index value
# when the split point is found
temp = data[head]
data[head] = data[U_index]
data[U_index] = temp
return U_index
# function call
def main():
data_set = [12, 50, 18, 21, 65, 31, 70, 14, 94, 67]
quick_sort(data_set, 0, len(data_set)-1)
print("sorted data : ", data_set)
if __name__ == "__main__":
main() | true |
dd5b28f4dfb81b071fcdfa81e5766eb9d03fa267 | kjdonoghue/DC_Python | /Algorithms/prime.py | 403 | 4.125 | 4 | number = int(input("Enter a number: "))
def prime(num):
if num == 1:
return False
elif num == 2 :
return True;
else:
for i in range(2,num):
if(num % i == 0):
return False
else:
return True
result = prime(number)
if result == True:
print("Prime Number")
else:
print("Not a Prime Number")
| true |
fd9aa67283858639ed3e4c2a84ff22ab81926efd | kjdonoghue/DC_Python | /Algorithms/elements.py | 614 | 4.375 | 4 | #Largest Element
numbers = [2,1,5,4,3]
def find_largest_element(list,):
largest_element = numbers[0]
for num in numbers:
if num > largest_element:
largest_element = num
return largest_element
largest_element = find_largest_element(numbers)
print(f"The largest element is {largest_element}")
#Smallest Element
def find_smallest_element(list):
smallest_element = numbers[0]
for num in numbers:
if num < smallest_element:
smallest_element = num
return smallest_element
smallest_element = find_smallest_element(numbers)
print(f"The smallest element is {smallest_element}")
| true |
6f126bba9459ef6740c9d821c3eb61973d8d8240 | Rublev09/edx600 | /6.00x/Ch2-2FingerExercise.py | 931 | 4.375 | 4 | x, y, z = 3, 5, 7
if x % 2 != 0:
if y % 2 != 0:
if z % 2 != 0:
if x > y and x > z:
print 'x is the greatest odd'
elif y > z:
print 'y is the greatest odd'
else:
print 'z is the greatest odd'
else:
if x > y:
print 'x is the greatest odd'
else:
print 'y is the greatest odd'
elif z % 2 != 0:
if x > z:
print 'x is the greatest odd'
else:
print 'z is the greatest odd'
else:
print 'x is the greatest odd'
elif y % 2 != 0:
if z % 2 != 0:
if y > z:
print 'y is the greatest odd'
else:
print 'z is the greatest odd'
else:
print 'y is the greatest odd'
elif z % 2 != 0:
print 'z is the greatest odd'
else:
print 'none of them are odd numbers'
| false |
b0ac4653a5a039e59960d393f38e47a96010c7e1 | XuShaoming/Programming_Language | /python3/Python3_Quick_Guide/command_line_arguments.py | 1,233 | 4.125 | 4 | #!/usr/bin/python3
'''
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
'''
'''
xu-Macbook:python3 xushaoming$ python3 command_line_arguments.py 1 2 3
Number of arguments: 4 arguments.
Argument List: ['command_line_arguments.py', '1', '2', '3']
'''
#!/usr/bin/python3
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)
if __name__ == "__main__":
main(sys.argv[1:])
'''
https://www.tutorialspoint.com/python3/python_command_line_arguments.htm
This code is useful for us to customize our own command line.
xu-Macbook:python3 xushaoming$ python3 command_line_arguments.py -i in -o out
Input file is " in
Output file is " out
''' | false |
03528e2126e9550a64efd14f1d2f1215432847a7 | patrickjdineen/python_day1 | /extra.py | 1,247 | 4.4375 | 4 | #Create a while loop that displays the names of the 30th to the 44th President - Hint create a list first
presidents = ["Calvin Coolidge", "Herbert Hoover" ,"Franklin D. Roosevelt","Harry S. Truman" ,"Dwight D. Eisenhower" ,"John F. Kennedy", "Lyndon B. Johnson" ,"Richard M. Nixon" ,"Gerald R. Ford", "James Carter", "Ronald Reagan","George H. W. Bush", "William J. Clinton", "George W. Bush", "Barack Obama"]
#for loop
for president in presidents:
print(president)
#while loop
p =0
while p < len(presidents):
print (presidents[p])
p+=1
#Write a loop to multiply all the numbers in a list. Sample List : [1, 2, 3, -4] Expected Output : -24
list = [1,2,3,-4]
i=0
sum=1
while i < len(list):
sum *= list[i]
i += 1
print(sum)
#Using Python Produce the following: (HINT: You would want to use a string, for loop[possibly multiple for loops], and concatenation for this)
#*
#**
#***
#****
#*****
star = "*"
for i in range(5):
print(star)
star+= "*"
#Sum of Integers Up To n
# Write a function, add_it_up(), that takes a single integer as input
# and returns the sum of the integers from zero to the input parameter.
#
# The function should return 0 if a non-integer is passed in.
def add_it_up(i):
j = 0
sum = 0
while j < i:
try:
j+=1
sum += j
except:
print(0)
add_it_up(7) | true |
48303341d9d83940a5613e57f26ed699bc8b22cc | ElleSowulewski/CIT228 | /Chapter5/weekend.py | 906 | 4.125 | 4 | import datetime
weekDays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
now = datetime.date.today()
dayOfWeek = now.weekday()
today = weekDays[dayOfWeek]
daysToWeekend = 6 - dayOfWeek
print(f"There are {daysToWeekend - 1} days until the weekend.")
quotePrinted = "false"
for left in weekDays[dayOfWeek:daysToWeekend]:
if today=="Sunday" and quotePrinted=="false":
print("Get ready to get back into the week!")
quotePrinted = "true"
elif (today=="Monday" or today=="Tuesday" or today=="Wednesday") and quotePrinted=="false":
print("Time to work!")
quotePrinted = "true"
elif today=="Thursday" and quotePrinted=="false":
print("Just one more day!")
quotePrinted = "true"
elif quotePrinted=="false":
print("Time off!")
quotePrinted = "true"
else:
print(left) | true |
7c771476c7d2595b97f5419186ae23ee0bd0153b | ElleSowulewski/CIT228 | /Chapter6/rivers.py | 796 | 4.1875 | 4 | rivers = {
"Nile": "Egypt",
"Mississippi": "United States",
"Yellow": "China",
}
print("-----------------------Rivers & Countries-----------------------")
for key, value in rivers.items():
print(f"The {key} River runs through the country {value}")
print("----------------------------------------------------------------")
print()
print("-----------------------------Rivers-----------------------------")
for key, value in rivers.items():
print(f"{key} River")
print("----------------------------------------------------------------")
print()
print("----------------------------Countries---------------------------")
for key, value in rivers.items():
print(value)
print("----------------------------------------------------------------")
print()
| false |
6027afb73dd21b54e4a2ec8672dba84f4ce73d74 | lintonjr/algoritmos_orlewilson | /05-06-2019-FUNCAO/1-E-B).py | 429 | 4.21875 | 4 | def Divisible(nC, nD):
nO = nC
if nC <= 0 or nD <= 0:
return print(f"O número {nO} não é divisível por {nD}")
while nC > 0:
nC -= nD
if nC == 0:
return print(f"O número {nO} é divisível por {nD}")
return print(f"O número {nO} não é divisível por {nD}")
num = int(input("Digite o número a ser divido: "))
div = int(input("Digite o divisor: "))
Divisible(num, div)
| false |
2c41bb9b2b64fe0963bb6eaf5f8e83df34d9af73 | akcauser/Python | /PythonCharArrayMethods/swapcase().py | 404 | 4.125 | 4 | ##swapcase metodu -> bu metod capitalize ve title ın benzeri bir metod
## olay şu küçük harfleri büyük - büyük harfleri küçük yapıyor
city = "İSTanb UL"
print(city.swapcase()) ## hatalıdır
for i in city:
if i == 'i':
city = city.replace('i','İ')
elif i == 'İ':
city = city.replace('İ','i')
else:
city = city.replace(i,i.swapcase())
print(city) | false |
7664dd7ae89ecff2720548e056ba464d929294d4 | TomasNiessner/Mi_primer_programa | /Tabla_multiplos_de_2.py | 500 | 4.1875 | 4 | #Modifica el programa de la tabla de multiplicar para que sólo muestre los resultados cuando son múltiplos de 2.
numero_tabla = int(input("Ingrese un número para obtener su tabla de multiplicación: "))
for numero in range(1,11):
if (numero_tabla * numero)%2 == 0:
print("{} * {} = {}".format(numero_tabla, numero, numero_tabla * numero))
#El signo "%" es la operación resto. En la linea 7 dije que si el "numero_tabla" multiplicado por "numero" da resto cero, se haga tal cosa.
| false |
ebc4f593b7ad2a3d483fbe911e56b6a24af3b73b | TomasNiessner/Mi_primer_programa | /Lista_vocales.py | 354 | 4.34375 | 4 | #Crea un programa que muestre por pantalla una lista de todas las vocales que aparecen en una string introducida por el usuario.
frase_usuario = input("Ingrese una frase: ")
vocales = ["a", "e", "i", "o", "u"]
l_vocales = []
for letra in frase_usuario:
if letra in vocales:
l_vocales.append(letra)
print("vocales: {}".format(l_vocales))
| false |
a7c2c9b82592af7529cc686f0b8986737661e662 | ravi-py/worksheet | /SquareofNaturalNumbers.py | 681 | 4.3125 | 4 | #Program for Difference between the sum of the squares of the first N natural numbers and the square of the sum.
N=int(input("Enter any Natural Number: "))
#The sum of the squares of the first N natural numbers S1
#By using the formula sum of the squares of the first N natural numbers
S1=((N*(N+1)*(2*N+1)))/6
#The square of the sum of the first N natural numbers is S2
#By using the formula The sum of the first N natural numbers
S2=((N*(N+1))/2)**2
#Difference between the sum of the squares of the first N natural numbers and the square of the sum T=S2-S1
T=S2-S1
print("Difference between the sum of the squares of the first N natural numbers and the square of the sum :",T)
| true |
5d4c337169316a89df3c64d7bb13c4fcea234b4c | Billoncho/Dice | /Dice.py | 770 | 4.25 | 4 | # Dice.py
# Billy Ridgeway
# Simulates rolling 5 dice.
import random # Imports the random library.
keep_going = True # Set the variable to true.
# Creates a while loop that will simulate rolling 5 dice and showing the
# user the results. The game will continue until the user presses any key
# other than Enter.
while keep_going:
dice = [0, 0, 0, 0, 0] # Sets all the dice to zero.
for i in range(5): # Rolls the dice.
dice[i] = random.randint(1, 6) # Assigns a random number to each di.
print("You rolled:", dice, ".") # Prints the user's dice.
answer = input("Keep going?") # Asks the user to continue or quit.
keep_going = (answer == "") # Evaluates the user's response.
| true |
1f507cc7d9e1367320d85914b4e443ce6f5c08fd | aaghassi2018/docstring-to-code | /code/hw3pr1.py | 2,637 | 4.1875 | 4 | # hw3pr1.py
#
#
# Name: Ashkon Aghassi
#
# Turtle graphics and recursion
#
import time
from turtle import *
from random import *
def tri(n):
"""Draws n 100-pixel sides of an equilateral triangle.
Note that n doesn't have to be 3 (!)
"""
if n == 0:
return # No sides to draw, so stop drawing
else:
forward(100)
left(120)
tri(n-1) # Recur to draw the rest of the sides!
def spiral(initialLength, angle, multiplier):
"""Spiral-drawing function. Arguments:
initialLength = the length of the first leg of the spiral
angle = the angle, in degrees, turned after each spiral's leg
multiplier = the fraction by which each leg of the spiral changes
"""
if initialLength <= 1:
return # No more to draw, so stop this call to spiral
else:
forward(initialLength)
left(angle)
spiral(initialLength*multiplier, angle, multiplier)
def chai(size):
"""Our chai function!"""
if (size < 5):
return
else:
forward(size)
left(90)
forward(size/2)
right(90)
chai(size/2)
right(90)
forward(size)
left(90)
chai(size/2)
left(90)
forward(size/2.0)
right(90)
backward(size)
return
def svtree(trunklength, levels):
"""svtree: draws a side-view tree
trunklength = the length of the first line drawn ("the trunk")
levels = the depth of recursion to which it continues branching
"""
if levels == 0:
return
else:
forward(trunklength)
left(30)
svtree(trunklength/2, levels-1)
right(60)
svtree(trunklength/2, levels-1)
left(30)
right(90)
svtree(trunklength/2, levels-1)
left(90)
backward(trunklength)
def snowflake(sidelength, levels):
"""Fractal snowflake function, complete.
sidelength: pixels in the largest-scale triangle side
levels: the number of recursive levels in each side
"""
flakeside(sidelength, levels)
left(120)
flakeside(sidelength, levels)
left(120)
flakeside(sidelength, levels)
left(120)
def flakeside(sidelength, levels):
"""draw one snowflake side
"""
if(levels == 0):
forward(sidelength)
return
else:
flakeside(sidelength/3, levels-1)
right(60)
flakeside(sidelength/3, levels-1)
left(120)
flakeside(sidelength/3, levels-1)
right(60)
flakeside(sidelength/3, levels-1) | true |
1315f8ab086b224d1552df8fc1110c02b876eb7a | myrainbowliuying/Python | /chapter3_4_list.py | 1,604 | 4.3125 | 4 | # 访问列表元素,增删查改等功能
'''
1.指出列表名和列表的索引即可。
2.可以调用任何对string适用的方法,例如:title()
3.列表第一个元素的索引是0,列表最后一个元素的索引是-1(经常需要在不知道列表长度时访问最后一个元素)
4、list.append() 在列表末尾添加一个元素
5、list.insert(索引,值)
6、删除 若知道索引,可以用 del list[索引] list.pop() 删除列表末尾的数,并且可以接着用他 也可以list.pop(索引) 若不知道值的位置,list.removal(value),会删除第一个满足要求的数
'''
#组织列表
'''
1、使用sort()进行永久性的排序。若要反向排序,只需要sort(reverse=True)
2、使用sorted()可以对列表进行临时排序
3、使用reverse()将列表反向
4、确定列表的长度 len(list)
'''
#操作数组
'''
1、遍历整个数组, for x in list :
'''
bicycles=['trek','cannoadale','specialized']
print(bicycles)
list1=['car','bus','plane','boat']
#临时排序
print(sorted(list1))
list2=bicycles+list1
print(list2)
#数字数组
'''
1、使用range(),包括前面不包括后面
2、使用range创建数字列表。
3、处理数组,包括sum(),min(),max()
4、列表解析 amazing!
5、切片,遍历切片
6、复制列表
'''
for value in range(1,5):
print(value)
numbers=list(range(1,6))
print(numbers)
#列表解析
squares=[values**2 for values in range(1,11)]
print(squares)
big_num=[int(n) for n in range(1,1000001)]
print(big_num[0:10])
print(min(big_num))
print(max(big_num))
print(sum(big_num)) | false |
b1906a07be56ccfc5f1ee4397489ad86b91d14ea | honestxll/honest_python | /tuple_and_list.py | 567 | 4.1875 | 4 | a_tuple = (12,3,4,5,6,9)
another_tuple = 32,4,5,6,89
a_list = [23,4,5,6,6]
a_list.remove(6)
a_list.insert(0, 1)
# 输出最后一位
print(a_list[-1])
# 输出前三位
print(a_list[0:3])
print(a_list[:3])
# 输出第三位以后的
print(a_list[3:])
# 查看列表中元素出现的次数
print(a_list.count(4))
def output(data_list):
data_list.sort()
for content in a_list:
print(content)
for index in range(len(a_list)):
print(index, a_list[index])
output(a_list)
multi_list = [
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]
]
# print(multi_list) | false |
362c392e05901d8c1d5f8a3978002dc005291811 | mlburgos/calculator-2 | /new_calculator.py | 2,619 | 4.21875 | 4 | """
calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from arithmetic import *
# # while True:
# read input
# tokenize input
# if the first token is 'q'
# quit
# else
# decide which math function to call based on first token
def my_reduce(func, num_list):
"""replicating reduce
"""
x = num_list[0]
i = 1
while i < len(num_list):
x = func(x, num_list[i])
i += 1
return x
def interactive_calc():
"""Receives user interactive requests from terminal.
"""
decimal = raw_input(" how many decimals would you like to see? \n")
while True:
request = raw_input("> ")
if request == "q":
return
print calculator(request, decimal)
def file_calculator(file_name):
"""reads file of calculator requests
"""
decimal = "2"
calc_file = open(file_name)
results_file = open("{}_results.txt".format(file_name.rstrip(".txt")), "w")
for line in calc_file:
output_line = line.rstrip() + " == " + calculator(line, decimal) + "\n"
results_file.write(output_line)
def calculator(request, decimal_input):
"""Parses string request and calls arithemtic functions.
"""
components = request.rstrip().split(" ")
math_func = components[0]
num_list = components[1:]
if (math_func == 'square' or math_func == 'cube') and len(num_list) > 1:
print "I can only take one argument for that operation"
return "InputError, stupid!"
try:
i = 0
while i < len(num_list):
num_list[i] = float(num_list[i])
i += 1
except ValueError:
print "numbers only, please! try again."
return "ValueError, stupid!"
if math_func == "+":
result = my_reduce(add, num_list)
elif math_func == "-":
result = my_reduce(subtract, num_list)
elif math_func == "*":
result = my_reduce(multiply, num_list)
elif math_func == "/":
result = my_reduce(divide, num_list)
elif math_func == "square":
result = square(num_list[0])
elif math_func == "cube":
result = cube(num_list[0])
elif math_func == "pow":
result = my_reduce(power, num_list)
elif math_func == "mod":
result = my_reduce(mod, num_list)
else:
print "I don't recognize your request :("
return "RequestError, stupid!"
output = "%." + decimal_input + "f"
return output % result
file_calculator("calc_requests.txt")
# interactive_calc() | true |
1450f161f4642d83f9d7792523e4ad4c250d728e | AleksanderZhariuk/turtle_race | /main.py | 1,254 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
def giving_turtles_names():
all_turtles = []
y_pos = -120
for color in colours:
y_pos += 40
one_of_the_turtle = Turtle(shape='turtle')
one_of_the_turtle.fillcolor(color)
one_of_the_turtle.penup()
one_of_the_turtle.goto(x=-230, y=y_pos)
one_of_the_turtle.speed(7)
all_turtles.append(one_of_the_turtle)
return all_turtles
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title='WHO WINS?', prompt='Type a colour: ').lower()
colours = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
turtles = giving_turtles_names()
if user_bet:
is_race_on = True
while is_race_on:
for turtle in turtles:
if turtle.xcor() > 230:
is_race_on = False
winning_turtle = turtle.fillcolor()
if winning_turtle == user_bet:
print(f"You've won! The {winning_turtle} turtle first!")
else:
print(f"You've lost! The {winning_turtle} turtle first!")
random_distance = random.randint(0, 10)
turtle.forward(random_distance)
screen.exitonclick() | true |
5e57a7cf04667faaaf9aedbccb04dd5f40c72c4a | SapneshNaik/python_assignment | /problem21/euclidean.py | 1,093 | 4.5 | 4 | #The Euclidean distance between two points in either the plane or 3-dimensional space
#measures the length of a segment connecting the two points.
#The Pythagorean Theorem can be used to calculate the distance between two points. In a 2d or 3d space.
import sys
import math
class Euclidean:
def __init__(self, point1, point2):
self.point1 = point1
self.point2 = point2
def distance_2d(self):
#(x2 -x1)
x_diff = self.point2[0] - self.point1[0]
#(y2-y1)
y_diff = self.point2[1] - self.point1[1]
# distance is square root of sum of square of x and y distances
square_sum = (x_diff * x_diff) + (y_diff * y_diff)
return math.sqrt(square_sum)
def distance_3d(self):
#(x2 -x1)
x_diff = self.point2[0] - self.point1[0]
#(y2-y1)
y_diff = self.point2[1] - self.point1[1]
#(z2-z1)
try:
z_diff = self.point2[2] - self.point1[2]
except:
print("Not a 3d object")
sys.exit()
# distance is square root of sum of square of x and y and z distances
square_sum = (x_diff * x_diff) + (y_diff * y_diff) + (z_diff * z_diff)
return math.sqrt(square_sum) | true |
46e12f221db619870b80a0633b7d95503f2ce55a | samhallam/isc-work | /python/strings.py | 684 | 4.25 | 4 | #Looping through a string
s= 'i love writing python'
for item in s:
print item,
# print the different element of 5
print s[4]
print s[-1]
print len(s)
#other things just picks out zero element as a string not a list
print s[0]
print s[0] [0]
print s[0] [0] [0]
#splitting a string to loop through a list of words
split_s = s.split()
print split_s
for item in split_s:
if item.find('i') > -1:
print "i found 'i' in : '{0}' ".format(item)
#useful aspects of strings
something = 'completely different'
print something.count('t')
print something.find('plete')
print something.split('e')
thing2 = something.replace('different', 'silly')
print thing2
| true |
27467532df5c2b8bf0b06f67fffcbe24e825c942 | samhallam/isc-work | /python/Numpy.py | 577 | 4.1875 | 4 | # Introduction to Numpy arrays
import numpy as np
x = [1,2,3,4,5,6,7,8,9,10]
a1 = np.array(x, np.int32)
a2 = np.array(x, np.float32)
print a1.dtype
print a2.dtype
# Creating arrays in different ways
a = np.zeros ((2,3,4))
print a
b= np.ones((2,3,4))
print b
c= np.arange((10))
print c
#indexing and slicing arrays
a = np.array([2,3.2,5.5,-6.4,-2.2, 2.4])
print a[1]
print a[1:4]
b = np.array([[2, 3.2, 5.5, -6.4, -2.2, 2.4],
[1, 22, 4, 0.1, 5.3, -9],
[3, 1, 2.1, 21, 1.1, -2]])
print b[:,3]
print b[1:4, 0:4]
print b[1: , 2]
| false |
badbbb1fb8b03f6130fa6f760adbfb302cb6e6f6 | martinkrebs/pyleague | /lib_table_printer.py | 1,091 | 4.34375 | 4 | class TablePrinter:
"""
the main method, print_table() takes a record set (list of tuples)
and displays them in a ascii table in terminal. Also adds the header row.
"""
def __init__(self, headings=('Team Name', 'w', 'd', 'l', 'pts')):
self.headings = headings
def print_row(self, row):
"""row is a tuple of column name strings"""
# 24char col width for name col, rest are 1 tab width
# calc n, how many chars you need to add to name lenght to make 23
n = 23 - len(row[0])
print('| ', row[0], ' '*n,
'| ', row[1], '\t',
'| ', row[2], '\t',
'| ', row[3], '\t',
'| ', row[4], '\t', ' |', sep='')
def print_headings(self):
self.print_row(self.headings)
def print_table_body(self, table):
for row in table:
self.print_row(row)
def print_table(self, table):
"""table is a list of rows (a list of tuples)"""
# print("\033c") # clear screen
self.print_headings()
self.print_table_body(table)
| true |
5102e736e07750d3cce8493c318a4810d7a230bf | shkh-odoo/odoo_trining | /main.py | 2,172 | 4.28125 | 4 | # Source from https://learnxinyminutes.com/docs/python/
# a =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#pop for deleting last value
#del for deleting by index
#remove for deleting by value
# b, c, *d = a
# for i, value in enumerate(a):
# print(i, value) # i is index and value is a[i]
# x = 0
# while x <= len(a)-1:
# print(a[x])
# x += 1
# exception handling
# python contains try, except, else, finally for exception handling
# else will run every time with exception occur
# finally will run every time in both try and except
# file handling
# contains method called "open"
# open(file_name, open_mode)
# just think variable is file so file.write() or file.read() will used to read or write content from file
# iterable
# filled_dict = {"one": 1, "two": 2, "three": 3}
# our_iterable = filled_dict.keys()
# our_iterator = iter(our_iterable) # this iter will work like a zip function but in very small case
# for i in our_iterator:
# print(i)
# or we can print our_iterator like :- next(our_iterator)
# args and kwargs
# args are used to take unlimited arguments like :- x = demo(1, 2, 3)
# args will return tuple like :- (1, 2, 3)
# kwargs are used tom take unlimited keyword arguments like :- demo(big=4, small=5)
# kwargs will return dict like :- {"big": 4, "small": 5}
# we can call globle defined variavles by useing goble keyword like :-
# x = 1
# def demo(number):
# globle x
# print(x+n)
# demo(1) it will print 2
# map function
# map is used to call parameteresd functions like demo(a, b)
# so we can call it like map(function_name, parameters)
# example: map(demo, 10, 20)
# example: list(map(demo, 20, 10)
# classmethod and staticmethod
# class abc():
# name = "Shubham" # class atribute
# @classmethod # will take cls argument for using class atrubutes
# def say(cls): # can not take self argument
# print(cls.name)
# @staticmethod # will not take cls or self argument
# # this method can not use the attrubuts and isinstances of the class
# def helo():
# print("Say Hello")
# print("hello" " world") # this is not error but answer will :- hello world means "hello world"
| true |
802348c67446cd0fb8f69324b03e42333b100e93 | Oso2016/ProjectPython | /proj01.py | 875 | 4.25 | 4 | # Name:
# Date:
# proj01: A Simple Program
# This program asks the user for his/her name and age.
# Then, it prints a sentence that says when the user will turn 100.
#
#
name = raw_input("Enter a your name:")
print name
age= raw_input("Enter your age:")
print age
if int(age) < 100:
birthday = raw_input("Have you had a birthday already this year? yes or no:")
print birthday
if birthday == "yes":
print name + " will turn 100 in the year",
print 100 - int(age) + 2017
if birthday == "no":
print name + " will turn 100 in the year",
print 100 - int(age) + 2016
if int(age) < 13:
print " You can watch G movies, and PG movies with parental guidance."
if int(age) == 13 or int(age) > 13:
print " You can watch G, PG, and PG13 movies."
if int(age) == 17 or int(age) > 17:
print "You can watch G, PG, PG13, and R movies."
| true |
64f68cab4aab30ebf508442f309c5dacc8daf518 | simpsons8370/cti110 | /P4HW2_DistanceTraveled_SimpsonShaunice.py | 1,196 | 4.15625 | 4 | #CTI - 110
#P4HW2 - Distance Traveled
#Shaunice Simpson
#April 15, 2021
#
def main():
again = 'y'
while again == 'y':
car_speed = float(input('Enter car\'s speed: '))
time_traveled = int(input('Enter time traveled: '))
if time_traveled <= 0:
print()
print('Error! time entered should be >0')
time_traveled = int(input('Enter time traveled: '))
print()
print('Time Distance')
print('-'*17)
for i in range(1,time_traveled+1):
print('{} {}'.format(i,car_speed*i))
again = input('would you like to enter a different time? (y for yes): ')
main()
#A varable is created for user to input a different time
#While the variable loop is equal to 'y', the user inputs a speed and time traveled
#The program will loop as long as the time traveled is not less than or equal to 0
#User is shown an error message and asks for another input for time traveled
#The program will loop from 1 to time traveled input
#Program will calculate, car speed x time traveled
#Program will display data in a table
#User will be asked if a different time will be entered
| true |
d5550b671832e6ac08ecc41c41e2665eb221b508 | simpsons8370/cti110 | /P2HW1_DistanceTraveled_ShauniceSimpson.py | 642 | 4.46875 | 4 | #Program calculating distanced traveled by car
#March 3, 2021
#CTI-110 P2HW1 - Distance Traveled
#Shaunice Simpson
#
car_speed = float(input('Enter car\'s speed: '))
time_traveled = float(input('Enter time traveled: '))
print()
print('Speed entered: ', car_speed)
print('Time entered: ', time_traveled)
print()
distance_traveled = car_speed * time_traveled
print('Distance Traveled', distance_traveled, 'miles')
#User inputs the car speed
#User inputs the time traveled
#Program displays the speed entered by user
#Program displays the time traveled by user
#Program multiples the speed and time and displays the product in miles
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.