blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0d56aa5047f1f172ffdc73425b26d25c9706dee7 | ShashikantBhargav/Bubble_sort- | /bubble_shor_using_list(user input).py | 446 | 4.1875 | 4 | print("program in assending order by user input:")
list1=[]
num=int(input('how many number you want to enter:-'))
print("enter values do you wants:")
for k in range(num):
list1.append(int(input("enter element:-")))
print("user entered list:",list1)
for j in range(len(list1)-1):
for i in range(len(list1)-1):
if list1[i]>list1[i+1]:
list1[i],list1[i+1]=list1[i+1],list1[i]
print("sorted list is:",list1)
| false |
93f1ec4e576c4d805a26e8e0a8b9adef0e021aca | rockchar/CODE_PYTHON | /Sets.py | 598 | 4.28125 | 4 | # sets are unordered collections of unique objects. They contain only one
# unique object
# Lets create a set
my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set)
# lets try to add a duplicate element to the set
my_set.add(3)
print(my_set)
#lets declare a list with duplicate objects
my_list = [1,2,2,3,3,4,4,4,4,4,5]
print(my_list)
#now lets convert it to a set
my_set_frm_list = set(my_list)
print(my_set_frm_list)
#in the above example we can see that the duplicate objects were eliminated
# the following will fail as sets are unordered
print(my_set_frm_list[4]) | true |
1bdd5f43e2f869c0c42681b8ade249c89e9258a0 | jao11/curso-em-video | /mundo01/aula006/Aula006.py | 1,280 | 4.1875 | 4 | # AULA 006
# n1=input('digite um número')
# n2=input('digite mais um número')
# s=n1+n2
# print('A soma vale',s)
# Infelizmente o algoritmo não vai funcionar se for escrito dessa forma.
# Para dar certo temos que escrever assim...
n1 = int(input('digite um número'))
n2 = int(input('digite mais um número'))
s = n1 + n2
print('A soma vale', s)
# print('A soma entre', n1,'e', n2, 'vale', s)
# format serve para ordenar as variaveis
print('A soma entre {0} e {1} vale {2}'.format(n1, n2, s))
# Os tipos primitivos são:
# int(inteiro)(7), float(real)(7.0), bool(lógicos)(true or false), str(caracter)('olá')
print('A soma vale{}'.format(s))
# pint(type(n1)) para ver a classe do n1 coloca-se type
print(type(n1))
print(type(s))
n3 = bool(input('Digite um valor'))
print(n3)
# se tiver type bool e não tiver nada escrito no "digite um valor" vai aparecer como false
# se tiver algo vai aparecer true
n4 = input('Digite algo:')
print(n4.isnumeric())
# Esse comando serve para dizer se é falso ou verdadeiro, se é possivel converter em número
print(n4.isalpha()) # ve se converte em alfabetico4
# Os comandos is( alguma coisa servem para teste de true or false
print(n4.isprintable())
n5 = float(input('Digite um valor'))
print(n5)
| false |
27e7c9c2bc894a1b298afa9c6b8b869d880d9c76 | MiroVatov/Python-SoftUni | /Python Advanced 2021/TUPLES AND SETS/Lab 02.py | 701 | 4.21875 | 4 | num_of_grades = int(input())
students_dict = {}
for _ in range(num_of_grades):
student_info = input().split()
student_name = student_info[0]
grade = float(student_info[1])
if student_name not in students_dict:
students_dict[student_name] = [grade]
else:
students_dict[student_name].append(grade)
for (stud, grades) in students_dict.items():
avg_grade = sum(grades) / len(grades)
# grades = ' '.join(map(lambda f: format(f, '.2f'), grades)) # format function that makes str formatted to float number, but it is still string
grades = [f"{mark:.2f}" for mark in grades]
print(f"{stud} -> {' '.join(grades)} (avg: {avg_grade:.2f})") | false |
c0c7854471f06aec35a86a9d09b5549773a22a6a | MiroVatov/Python-SoftUni | /PYTHON OOP/INHERITANCE/Labs/stack_of_strings/stack.py | 610 | 4.15625 | 4 |
class Stack:
def __init__(self):
self.data = []
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
# peek()method will show us the top value in the Stack
def peek(self):
return self.data[-1]
def is_empty(self):
return len(self.data) == 0
def __str__(self):
new_data = ', '.join(str(s) for s in self.data[::-1])
return f"[{str(new_data)}]"
st = Stack()
data_to_push = 'carrot', 'apple'
st.push(data_to_push)
print(st.peek())
print(st.is_empty())
print(st) | false |
aa7a877fb5450c27b78fbf7f026991d1e9289c7e | MiroVatov/Python-SoftUni | /Python Advanced 2021/EXAMS_PREPARATION/Exam 27 June 2020/02 snake.py | 2,730 | 4.125 | 4 | field_size = int(input())
snake_field = [list(input()) for _ in range(field_size)]
def check_starting_position(field, start):
for row in range(len(field)):
if start in field[row]:
return row, field[row].index(start)
def is_outside(cur_row, cur_col, size):
if 0 <= cur_row < size and 0 <= cur_col < size:
return False
return True
def find_burrow(field, burrow):
burrows = 0
for row in range(len(field)):
if burrow in field[row]:
burrows += 1
if burrows == 2:
return row, field[row].index(burrow)
def print_snake_filed(field):
for row in range(len(field)):
print(''.join(field[row]))
START = 'S'
BURROW = 'B'
# 'S' -> snake starting position
# '*' -> food
# 'B' -> burrow must be 2 with B's
# '-' -> empty positions
# '.' -> snake trails
food_qty = 0
starting_row, starting_col = check_starting_position(snake_field, START)
current_row, current_col = starting_row, starting_col
move_commands = ["up", "down", "left", "right"]
UP_MOVE = (-1, 0)
DOWN_MOVE = (1, 0)
LEFT_MOVE = (0, -1)
RIGHT_MOVE = (0, 1)
while food_qty < 10:
direction = input()
last_row, last_col = current_row, current_col
if direction in move_commands:
if direction == 'up':
current_row += UP_MOVE[0]
current_col += UP_MOVE[1]
elif direction == 'down':
current_row += DOWN_MOVE[0]
current_col += DOWN_MOVE[1]
elif direction == 'left':
current_row += LEFT_MOVE[0]
current_col += LEFT_MOVE[1]
elif direction == 'right':
current_row += RIGHT_MOVE[0]
current_col += RIGHT_MOVE[1]
if is_outside(current_row, current_col, field_size):
snake_field[last_row][last_col] = '.'
print("Game over!")
break
if snake_field[current_row][current_col] == '*':
food_qty += 1
snake_field[last_row][last_col] = '.'
snake_field[current_row][current_col] = 'S'
elif snake_field[current_row][current_col] == '-':
snake_field[last_row][last_col] = '.'
snake_field[current_row][current_col] = 'S'
elif snake_field[current_row][current_col] == 'B':
burrow_end_position = find_burrow(snake_field, BURROW)
snake_field[last_row][last_col] = '.'
snake_field[current_row][current_col] = '.'
current_row, current_col = burrow_end_position[0], burrow_end_position[1]
snake_field[current_row][current_col] = 'S'
if food_qty >= 10:
print(f"You won! You fed the snake.")
print(f"Food eaten: {food_qty}")
print_snake_filed(snake_field) | false |
d4eb863d441ae9a67d333784662b3aa35f4cc745 | xd-lpc/sharemylove | /ex39.py | 1,060 | 4.125 | 4 | #create a mapping of status to abbreviation
states = {
'Oregon':'OR',
'Florida': 'FL',
'California':'NY',
'Michigan':'MI'
}
#create a basic set of status and some cities in them
cities = {
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksonville'
}
#add more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
#print out some cities
print('-' * 20)
print("NY state has: ",cities['NY'])
print('OR state has: ', cities['OR'])
#print out some state
print('-' * 20)
print("Michigan's abbreviation is: ",states['Michigan'])
#print every abbreviation
print('-' * 20)
for state,abbrev in states.items():
print("%s is abbreviated %s" %(state,abbrev))
#print every city in state
print('-' * 20)
for abbrev,city in cities.items():
print("%s has the city %s" %(abbrev,city))
#now do both at the same time
print('-' * 20)
for state,abbrev in states.items():
print("%s is abbreviated %s, and has city %s" %(state,abbrev,cities[abbrev]))
state = states.get('Texas',None)
if not state:
print("sorry no Texas")
| false |
6bcdb23587171691e25cd375ea30f5356487dcc9 | vensder/codeacademy_python | /shout.py | 289 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def shout(phrase):
if phrase == phrase.upper():
return "YOU'RE SHOUTING!"
print phrase
else:
return "Can you speak up?"
print "Hello!"
phrase = raw_input("Enter yours phrase:\n")
print shout(phrase)
| true |
2bb4c43c58c24f07a6b0a2e30ae5e3a1593e1ef6 | sipakhti/code-with-mosh-python | /Data Structure/Dictionaries.py | 1,002 | 4.25 | 4 | point = {"x": 1, "y": 2}
point = dict(x=1, y=2)
point["x"] = 10 # index are names of key
point["z"] = 20
print(point)
# to make sure the program doesnt crash due to invalid dict key
if "a" in point:
print(point["a"])
# Alternative approach using .get function and it makes the code cleaner
print(point.get("a", 0))
# for deleting an item
del point["x"]
print(point)
# itereating over a dictionary. When looping only the key is returned
for key in point:
print(key, point[key])
# .item funtion returns a tuple of (key, value) pair which can be unpacked like any other tuple
for key, value in point.items():
print(key, value)
# this comprehensioin can also be used with sets and dictionaries
values = [x * 2 for x in range(5)]
# Comprehnsion method for sets
sets = {x * 2 for x in range(5)}
print(sets)
# Comprehension metthod for dictionary
dicts = {x: x*2 for x in range(5)}
print(dicts)
# Topic for next lecture -- Genearator object
tupes = (x * 2 for x in range(5))
print(tupes) | true |
b5fc18297b318ff88610adf0cb3d3448de671d31 | sipakhti/code-with-mosh-python | /Data Structure/Unpacking Operator.py | 440 | 4.21875 | 4 | numbers = [1, 2, 3]
print(*numbers)
print(1, 2, 3)
values = list(range(5))
print(values)
print(*range(5), *"Hello")
values = [*range(5), * "Hello"]
first = [1, 2]
second = [3]
values = [*first, *second]
print(*values)
first = dict(x=1)
second = dict(x=10, y=2)
# incase of multiple values with similar keys, the last value will be used as in this case the value from the second dict
combined = {**first, **second, "Z":1}
print(combined) | true |
307eccd04d95e8e169f1b1cf743b10fb42686268 | sipakhti/code-with-mosh-python | /Control Flow/Ternary_Operator.py | 240 | 4.15625 | 4 | age = 22
if (age >= 18):
message = "Eligible"
else:
message = "Not Eligible"
print(message)
# more clearner way to do the same thing
age = 17
message = "Eligible" if age >= 18 else "Not Eligible" # ternary Operator
print(message) | true |
64fef01dcc207fc7e1d965d319f03433672f2429 | EarthCodeOrg/earthcode-curriculum | /modules/recursive_to_iterative.py | 544 | 4.15625 | 4 | # Recursive to Iterative
# Approach 1: Simulate the stack
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
def factorial_iter(n):
original_n = n
results = {}
inputs_to_resolve = [n]
while inputs_to_resolve:
n = inputs_to_resolve.pop()
if n < 2:
results[n] = 1
else:
# we want n-1
if n-1 not in results:
else:
inputs_to_resolve.append(n)
inputs_to_resolve.append(n-1)
else:
results[n] = n*results[n-1]
# Approach 2: Tail End Recursion
| true |
f2a9b7ec51fa931682743a4957d34a9a80441679 | ModellingWebLab/chaste-codegen | /chaste_codegen/_script_utils.py | 676 | 4.15625 | 4 | import os
def write_file(file_name, file_contents):
""" Write a file into the given file name
:param file_name: file name including path
:param file_contents: a str with the contents of the file to be written
"""
assert isinstance(file_name, str) and len(file_name) > 0, "Expecting a file path as string"
assert isinstance(file_contents, str), "Contents should be a string"
# Make sure the folder we are writing in exists
path = os.path.dirname(file_name)
if path != '':
os.makedirs(path, exist_ok=True)
# Write the file
file = open(file_name, 'w')
file.write(file_contents)
file.close()
| true |
d0bf5cbec6cc10cecfd3a5e556851908df86110e | pliz/PDF-guard | /pdf-encryptor.py | 651 | 4.15625 | 4 | from PyPDF2 import PdfFileWriter, PdfFileReader
pdfWriter = PdfFileWriter()
# Read the pdf file which will be encrypted
pdf = PdfFileReader("example.pdf")
for page_num in range(pdf.numPages):
pdfWriter.addPage(pdf.getPage(page_num))
# Encryption process goes here
passw = input('Enter your password: ')
pdfWriter.encrypt(passw)
print('Password was set successfully !')
setNewName = input('What will you name your encrypted pdf? (without ".pdf") : ')
newPdfName = str(setNewName) + '.pdf'
# Create a new encrypted PDF
with open(newPdfName, 'wb') as f:
pdfWriter.write(f)
f.close()
print('Excellent! You have secured your PDF file!')
| true |
2a185cc736922ae8baff835e5d0b9b3727dc7fc3 | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q139_word_break.py | 1,980 | 4.28125 | 4 | import re
from typing import List
def wordBreak(s: str, wordDict: List[str]) -> bool:
"""
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
• 1 <= s.length <= 300
• 1 <= wordDict.length <= 1000
• 1 <= wordDict[i].length <= 20
• s and wordDict[i] consist of only lowercase English letters.
• All the strings of wordDict are unique.
"""
assert 1 <= len(s) <= 300, "Length of s must be between 1 and 300"
assert 1 <= len(wordDict) <= 1000, "Length of wordDict must be between 1 and 1000"
assert re.search("[a-z]", s), "s must consist of only lowercase English letters"
for word in wordDict:
assert 1 <= len(word) <= 20, "Length of word in wordDict must be between 1 and 20"
assert re.search("[a-z]", word), "word in wordDict must consist of only lowercase English letters"
assert len(wordDict) == len(set(wordDict)), "All the strings in wordDict must be unique"
dp = [False for _ in range(len(s) + 1)]
dp[-1] = True
for i in reversed(range(len(s))):
for word in wordDict:
if i + len(word) <= len(s) and s[i:i+len(word)] == word:
dp[i] = dp[i+len(word)]
if dp[i]:
break
return dp[0]
| true |
0c822fefe2815bf1f401a6ae0e5ca175fd252ee8 | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q46_permutations.py | 1,137 | 4.125 | 4 | from typing import List
def permute(nums: List[int]) -> List[List[int]]:
"""
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
Constraints:
• 1 <= nums.length <= 6
• -10 <= nums[i] <= 10
• All the integers of nums are unique.
"""
assert 1 <= len(nums) <= 6
for num in nums:
assert -10 <= num <= 10
assert len(nums) == len(set(nums))
resultList = []
visited = set()
def backtrack(visitedSet, permutation):
if len(permutation) == len(nums):
resultList.append(permutation.copy())
for i in range(len(nums)):
if i not in visited:
visitedSet.add(i)
backtrack(visitedSet, permutation + [nums[i]])
visitedSet.remove(i)
backtrack(visited, [])
return resultList
| true |
6b91e70df04c6feb54be4da4c340b151951f0a4e | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q169_majority_element.py | 1,126 | 4.28125 | 4 | from typing import List
def majorityElement(nums: List[int]) -> int:
"""
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Constraints:
• n == nums.length
• 1 <= n <= 5 * 10 ** 4
• -10 ** 9 <= nums[i] <= 10 ** 9
"""
assert 1 <= len(nums) <= 5 * 10 ** 4
for num in nums:
assert -10 ** 9 <= num <= 10 ** 9
## Moore Voting Algorithm
# count = 0
# candidate = 0
# for num in nums:
# if count == 0:
# candidate = num
# if num == candidate:
# count += 1
# else:
# count -= 1
# return candidate
numDict = {}
for num in nums:
if num not in numDict:
numDict[num] = 0
numDict[num] += 1
if numDict[num] > len(nums) // 2:
return num | true |
cd2d86cd6a9e91412e5e4eaac9d33716291177e2 | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/CSES_Problem_Set/Q2_missing_number.py | 1,248 | 4.125 | 4 | """
You are given all numbers between 1,2,…,n except one.
Your task is to find the missing number.
Input
The first input line contains an integer n.
The second line contains n−1 numbers. Each number is distinct and between 1 and n (inclusive).
Output
Print the missing number.
Constraints
2 ≤ n ≤ 2*10^5
Example
Input:
5
2 3 1 5
Output:
4
"""
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
def missing_number(args):
assert 2 <= args.number <= 2 * 10**5, "Please input another integer within the range [2, 200000]"
assert len(args.number_array) == args.number-1, "There are more than 1 missing number in the array"
target_sum = int(args.number * (args.number+1) / 2)
current_sum = sum(args.number_array)
missing_num = target_sum - current_sum
logger.info(f"Missing number in the given array is {missing_num}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tools to find missing number")
parser.add_argument('-n', dest="number", type=int, help="Integer n", required=True)
parser.add_argument('-array', type=int, dest="number_array", nargs='+')
args = parser.parse_args()
missing_number(args)
| true |
856d259f74a1016e5cc43bfe2bc9bb714108ed2c | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q20_valid_parenthesis.py | 1,243 | 4.28125 | 4 | def isValid(s: str) -> bool:
"""
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Constraints:
• 1 <= s.length <= 10 ** 4
• s consists of parentheses only '()[]{}'.
"""
assert 1 <= len(s) <= 10 ** 4, "Length of string must be between 1 and 10 ** 4"
for character in s:
assert character in ['(', ')', '[', ']', '{', '}']
track_left_bracket = []
bracket_dict = {'(': ')', '[': ']', '{': '}'}
for bracket in s:
if bracket in bracket_dict.keys():
track_left_bracket.append(bracket)
elif len(track_left_bracket) == 0 or bracket_dict[track_left_bracket.pop()] != bracket:
return False
return True if len(track_left_bracket) == 0 else False
| true |
6ad68ea092a6435db680bd485a1279b2de19292d | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q11_container_with_most_water.py | 1,501 | 4.25 | 4 | from typing import List
def container_with_most_water(height: List[int]) -> int :
""""
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
Find two lines, which, together with the x-axis forms a container,
such that the container contains the most water.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1]
Output: 1
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
Constraints:
• n == height.length
• 2 <= n <= 3 * 104
• 0 <= height[i] <= 3 * 10 ** 4
"""
assert 2 <= len(height) <= 3 * 104, "Length of height is strictly between 2 and 3 * 104"
for i in range(len(height)):
assert 0 <= height[i] <= 3 * 104, "Length of height is strictly between 2 and 3 * 104"
max_volume = 0
n = len(height)
i = 0
j = n - 1
while i < j:
max_volume = max(max_volume, min(height[i], height[j]) * (j - i))
if height[i] < height[j]:
i += 1
else:
j -= 1
return max_volume
| true |
2be28d3c7f1d27878116b489ddf78409f4fe1a2c | bheinks/2018-sp-a-puzzle_4-bhbn8 | /priorityqueue.py | 1,194 | 4.21875 | 4 | class PriorityQueue:
"""Represents a custom priority queue instance. While Python has a
PriorityQueue library available, this is more efficient because it sorts on
dequeue, rather than enqueue."""
def __init__(self, key, items=[]):
"""Initializes a PriorityQueue instance.
Args:
key: The function that will act as the sort key of our queue.
items: Any initial queue items.
"""
self.key = key
self.items = items
def enqueue(self, item):
"""Add an item to the queue.
Args:
item: The item that's being added.
"""
self.items.append(item)
def dequeue(self):
"""Sort using our key function and pop an item from the queue.
Returns:
The item at the top of the queue, post-sorting.
"""
# reverse the sort as pop takes the last item from the queue
self.items.sort(key=self.key, reverse=True)
return self.items.pop()
def __len__(self):
"""Overload __len__ to return length of queue.
Returns:
The number of items in our queue.
"""
return len(self.items)
| true |
ec9ab3c13b26dfbfbf5edf2225ae6870f59a7e80 | lucguittard/DS-Unit-3-Sprint-2-SQL-and-Databases | /module2-sql-for-analysis/practice.py | 946 | 4.21875 | 4 | # Working with sqlite
# insert a table
# import the needed modules
import sqlite3
import pandas as pd
# connect to a database
connection = sqlite3.connect("myTable.db")
# make a cursor
curs = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE emp (staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE);"""
# execute the statement
curs.execute(sql_command)
# SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUE (23, "Joe", "Walker", "M", "2015-04-11");"""
curs.execute(sql_command)
# another data insertion command
sql_command = """INSERT INTO emp VALUE (40, "Kam", "Greene", "F", "2004-07-23");"""
curs.execute(sql_command)
# save the changes made to the database file
connection.commit()
# close the connection
connection.close()
# may now run SQL queries on the populated database (continue to part 2)
| true |
23b32a35acc060b021706f17754c0e1479259025 | saranaweera/dsp | /python/q8_parsing.py | 701 | 4.3125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import pandas as pd
data = pd.read_csv('football.csv')
data['AbsGoalDiff'] = (abs(data['Goals'] - data['Goals Allowed']))
print('Team with the smallest difference in for and against goals: {}'.format(
data.loc[data['AbsGoalDiff'].idxmin(),'Team']
))
| true |
656a32a3781605c1f68539cfcdc3e8de98bf4181 | sivaneshl/real_python | /implementin_linked_list/implementing_a_own_linked_list.py | 1,765 | 4.46875 | 4 | from linked_list import LinkedList, Node
# using the above class create a linked list
llist = LinkedList()
print(llist)
# add the first node
first_node = Node('a')
llist.head = first_node
print(llist)
# add subsequent nodes
second_node = Node('b')
third_node = Node('c')
first_node.next = second_node
second_node.next = third_node
print(llist)
# create the linked list by passing in the nodes list
llist = LinkedList(list('abcde'))
print(llist)
# traversing through the linked list
for e in llist:
print(e)
# inserting an element to the first of the linked list
llist.add_first(Node('x'))
llist.add_first(Node('y'))
print(llist)
# inserting an element to the last of the linked list
llist.add_last(Node('f'))
llist.add_last(Node('g'))
print(llist)
# inserting a node in between
# adding to an empty linked list
llist = LinkedList()
# llist.add_after('a', Node('b')) # exception
print(llist)
# adding an element after a target node
llist = LinkedList(list('abcde'))
llist.add_after('c', Node('cc'))
print(llist)
# attempt to add after a non-existent target node
# llist.add_after('f', Node('g')) # exception
print(llist)
# inserting a node before a target node
llist.add_before('c', Node('bb'))
print(llist)
llist.add_before('a', Node('zz'))
print(llist)
# removing a node
llist.remove_node('zz')
print(llist)
llist.remove_node('cc')
llist.remove_node('bb')
print(llist)
# get the node at position i
print(llist.get(3))
# print(llist.get(7)) # exception
# get the node at position i using subscript
print(llist[3])
# print(llist[7]) # exception
# get the reversed linked list
print(llist.reverse())
# get the length of the linked list
print(len(llist))
print(llist.__len__())
| true |
37898e1d98f7a08c52d2dc6fc80779c54ba60685 | nnamon/ctf101-systems-2016 | /lessonfiles/offensivepython/11-stringencodings.py | 864 | 4.125 | 4 | #!/usr/bin/python
def main():
sample_number = 65
# We can get binary representations for a number
print bin(sample_number) # Results in 0b1000001
# We can also get hex representations for a number:
print hex(sample_number) # Results in 0x41
# Also, octal:
print oct(sample_number) # Results in 0101
sample_text = "ABCD"
# Often, we want to convert a string into hex for reason that will be more
# apparent as you progress further up in CTFs
print sample_text.encode("hex") # Results in 41424344
# Conversely, we can also decode from a hex string
print "41424344".decode("hex") # Results in ABCD
# There are other useful codecs as well:
print "SGVsbG8=".decode("base64") # Results in Hello
print "Obawbhe".decode("rot13") # Results in Bonjour
if __name__ == "__main__":
main()
| true |
a5ad8c8a3e2c0a6ac172e08129f092bb638768a5 | ZhangJiaQ/LintCode_and_other_homework | /LintCode/字符串处理/LintCode415.py | 935 | 4.25 | 4 | # 有效回文串
# 给定一个字符串,判断其是否为一个回文串。只包含字母和数字,忽略大小写。
# 样例
# "A man, a plan, a canal: Panama" 是一个回文。
# "race a car" 不是一个回文。
# 解题思路:由于需要忽略标点与空格,只对字母和数字进行回文判定,所以我们需要先对字符串进行处理,遍历字符串并使用
# isalpha()方法与isnumeric()方法取得字母与数字,然后将字母全变为小写,进行回文判定。
class Solution:
# @param {string} s A string
# @return {boolean} Whether the string is a valid palindrome
def isPalindrome(self, s):
# Write your code here
new_string = ''
for i in s:
if i.isalpha() or i.isnumeric():
new_string += i
if new_string.lower() == new_string.lower()[::-1]:
return True
else:
return False | false |
d57e662d520f5ff40408d2d410584cb32942d4aa | elrapha/Lab_Python_01 | /zellers.py | 1,672 | 4.75 | 5 | """
Zeller’s algorithm computes the day of the week on which a given date will fall (or fell). In
this exercise, you will write a program to run Zeller’s algorithm on a specific date. You
will need to create a new file for this program, zellers.py. The program should use the
algorithm outlined below to compute the day of the week on which the user’s birthday fell
in the year you were born and print the result to the screen.
Let A, B, C, D denote integer variables that have the following values:
A = the month of the year, with March having the value 1, April the value 2, ... December
the value 10, and January and February being counted as months 11 and 12 of the
preceding year (in which case, subtract 1 from C)
B = the day of the month (1, 2, 3, ... , 30, 31)
C = the year of the century (e.g. C = 89 for the year 1989)
D = the century (e.g. D = 19 for the year 1989)
Note: if the month is January or February, then the preceding year is used for
computation. This is because there was a period in history when March 1st, not January
1st, was the beginning of the year.
"""
A=raw_input('Enter month as a number between 1 and 12: ')
B=raw_input('Enter the day of the month as numbers between 1 and 31: ')
year=raw_input('Enter year (eg. 1999): ')
A=int(A)
A=A-2
if A<0:
A=A+12
B=int(B)
C=int(year)%100
D=int(year)/100
if A==11:
print '11th month'
C=C-1
if A==12:
print '12th month'
C=C-1
# print A,' ',B,' ',C,' ',D
W = (13*A - 1) / 5
X=C/4
Y=D/4
Z = W + X + Y + B + C - 2*D
R=Z % 7
months=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
print A+2,'/',B,'/',year,' falls on ' + months[R]
| true |
1faf7950718cd67c1bd3dc182059763b1c784c5c | JosephLiu04/Wave3 | /PythagTheorem.py | 317 | 4.53125 | 5 | from math import sqrt
Side1 = float(input("Input the length of the shorter first side:"))
Side2 = float(input("Input the length of the shorter second side: "))
def Pythag_theorem():
Side3 = sqrt((Side1 * Side1) + (Side2 * Side2))
return Side3
print("The length of the hypotenuse is", str(Pythag_theorem())) | true |
9902409c31c852fd0878827aaa3b025099f997af | mrfabroa/ICS3U | /Archives/2_ControlFlow/conditional_loops.py | 1,611 | 4.34375 | 4 | __author__ = 'eric'
def example1():
# initialize the total and number
total = 0
number = input("Enter a number: ")
# the loop condition
while number != -1:
# the loop statements
total = total + number
number = input("Enter a number: ")
print "The sum is", total
def example1_1():
"""
write a program that uses a while loop to output the numbers from 1 to 10
:return:
"""
# for loop style
for i in range(1,11):
print i
# while loop version
count = 1 # initialize count at 1
# repeat while count <=10
while count <= 10:
print count # output count
count += 1
def example2():
# Set the number and number of entries to be 0
total = 0
entries = 0
# Read a number from the user
number = input("Enter a number: ")
# while the number is not -1
while number != -1:
# sum = sum + number
total = total + number
# number of entries = number of entries + 1
entries += 1
# read a number from the user
number = input("Enter a number: ")
# Output sum/number of entries
print float(total)/entries
def largest():
biggest = 0
number = input("Enter number here: ")
while number != -1:
if number > biggest:
biggest = number
number = input("Enter number here: ")
print biggest
def infinite():
# repeat while count <=10
count = 1
while count <= 10:
print count # output count
#count += 1 --> commenting this out causes an infinite loop
| true |
c2e42318e56cf09abd5c1a456a4e3222a80e5226 | mrfabroa/ICS3U | /Archives/3_Lists/3_1_practice.py | 1,341 | 4.1875 | 4 | __author__ = 'eric'
def middleway(list_a, list_b):
"""
Given 2 int lists, list_a and list_b, each length 3,
write a function middle_way(list_a,list_b) that returns
a new list length 2 containing their middle elements.
:param list_a: int[]
:param list_b: int[]
:return: int[]
"""
list_c = [list_a[1], list_b[1]]
return list_c
def common_end(list_a, list_b):
"""
Given 2 lists of ints, list_a and list_b,
write a function common_end(list_a, list_b) and
return True if they have the same first element
or they have the same last element.
Both lists will be length 1 or more.
:param list_a: int[]
:param list_b: int[]
:return: Boolean
"""
if (list_a[0] == list_b[0]) or (list_a[-1] == list_b[-1]):
return True
else:
return False
def max_end3(list3):
"""
given a list (list3) of ints length 3, figure out which is
larger between the first and last elements in the list,
set all the other elements to be that value. Return the changed list.
:param list3: int
:return: int[]
"""
# compare first and last elements
if list3[0] > list3[2]:
list3[1] = list3[0]
list3[2] = list3[0]
elif list3[0] < list3[2]:
list3[0] = list3[2]
list3[1] = list3[2]
return list3
| true |
51c4f09686dfc3e7b2cf59a1a549ba5ac1fb7806 | shijietopkek/cpy5p1 | /q1_fahrenheit_to_celsius.py | 268 | 4.25 | 4 | # q1_fahrenheit_to_celsius.py
# Fahrenheit to Celsius converter
# get input
Fahrenheit = float(input("Enter Fahrenheit temperature: "))
# convert temperature
celsius = (5/9) * (Fahrenheit - 32)
# output result
print("temperature in celsius is", celsius)
| false |
8b505676a08ba224903433f7546e35ae8f441edb | manhtruong594/vumanhtruong-fundamental-c4e24 | /Fundamental/Session04/homework/SeriousEx1.py | 1,313 | 4.125 | 4 | items = ["T-Shirt", "Sweater"]
print("Here is my items: ", sep=" ")
print(*items, sep=", ")
loop = True
while loop:
cmd = input("Welcome to our shop, what do u want (C, R, U, D or exit)? ").upper()
if cmd == "R":
print("Our items: ", *items, sep=", ")
elif cmd == "C":
new = input("Enter new item: ")
items.append(new)
print("Our items: ", *items, sep=", ")
elif cmd == "U":
while True:
position_update = int(input("Update position? "))
if 0 > position_update or position_update > len(items):
print("No items in this position, try again!")
else:
update = input("Update to new item: ")
items[position_update - 1] = update
print("Our items: ", *items, sep=", ")
break
elif cmd == "D":
while True:
position_del = int(input("Delete position? "))
if 0 > position_del or position_del > len(items):
print("No items in this position, try again!")
else:
items.pop(position_del)
print("Our items: ", *items, sep=", ")
break
elif cmd == "exit":
loop = False
else:
print("Only chose C, R, U, D or exit!! Try again!") | true |
24979e4b645fd55c678190b244fd9ee3436232d7 | sbolla27/python-examples | /class2/calculator_class.py | 748 | 4.125 | 4 | class Calculator(object):
def __init__(self, num1, num2, num3=0):
self.x = num1
self.__y = num2
self.z = num3
def add(self):
return self.x + self.__y + self.z
def sub(self):
return self.x - self.__y
def multi(self):
return self.x * self.__y
def divide(self):
return self.x/self.__y
class AdvancedCalculator(Calculator):
def modulo(self):
return self.x % self.__y
def divide(self):
print(__y)
try:
return self.x/self.__y
except:
print("you cannot divide by zero")
# cal1 = AdvancedCalculator(1)
# print(cal1.divide())
cal2 = Calculator(1,2)
print(cal2.add())
cal3 = Calculator(1,2,3)
print(cal3.add()) | false |
7d34ce21348e849a06da1b04a3c40c611587261a | fabiangothman/Python | /fundamentals/4_strings.py | 811 | 4.21875 | 4 | myStr = "hello_all_world"
#Properties of an object: command "dir"
#print(dir(myStr))
print(myStr.upper())
print(myStr.lower())
print(myStr.swapcase())
print(myStr.capitalize())
print(myStr.replace("hello", "bye").upper()) #Method chaining (Métodos encadenados)
print(myStr.count("l"))
print(type(myStr.count("l")))
print(myStr.startswith("he"))
print(type(myStr.startswith("he")))
print(myStr.endswith("world"))
print(type(myStr.endswith("world")))
print(myStr.split("_"))
print(type(myStr.split("_")))
print(myStr.find("l"))
print(type(myStr.find("l")))
print(myStr.index("l"))
print(type(myStr.index("l")))
print(myStr[4])
print(myStr[-3])
#Length
print(f"The text length is: {len(myStr)}")
print("The text length is: " + len(myStr).__str__())
print("The text length is: {0}".format(len(myStr)))
| false |
99ec192ac77df5906950a92b131e73665a76a06a | Cole-Hayson/L1-Python-Tasks | /Names List.py | 1,136 | 4.25 | 4 | names = ["Evi", "Madeleine", "Dan", "Kelsey", "Cayden", "Hayley", "Darian"]
user_name = input("Enter a name")
if user_name in names:
print("That name is already on the list!")
else:
print("The name you chose is not on the list.")
if user_name != names:
replace = input("Would you like to replace one of the names on the list with the name you picked? yes or no.")
if replace.lower() == "yes":
names = ["Evi", "Madeleine", user_name, "Kelsey", "Cayden", "Hayley", "Darian"]
print("We have replaced Dan with the name you have chosen. You are now on the list.")
print(names)
elif replace.lower() == "no":
print("You have chosen to not replace a name on the list.\n")
add = input("Would you like to add the name you picked to the list? yes or no.")
if add.lower() == "yes":
names = ["Evi", "Madeleine", "Dan", "Kelsey", "Cayden", "Hayley", "Darian", user_name]
print("The name you picked has been added to the list.")
print(names)
elif add.lower() == "no":
print("You have chosen to not add the name to the list.")
| true |
bd64fadca3071891ce36d42ddfdd8b1ddc96901b | PuneetPowar5/Small-Python-Projects | /fibonacciSequence.py | 323 | 4.21875 | 4 | print("Welcome to the Fibonacci Sequence Generator\n")
maxNum = int(input("How many numbers of the sequence do you want to see? \n"))
maxNum = int(maxNum)
a = 0
b = 1
c = 0
print("\n")
for num in range(0, maxNum):
if(num <= 1):
c = num
else:
c = a + b
a = b
b = c
print(c) | true |
34adf55b11a6b6c45f7b9d25d49b385a3e7cd8c7 | karendi/python | /excercise39.py | 1,737 | 4.21875 | 4 | counties = {
'nairobi' :"NRB" ,
'Thika':"Tka" ,
'Githurai':"GRI" ,
'Kakamega':"KKGA",
'Webuye':"WBE",
'Kisumu':"KSM"
}
#adding towns to the different counties we have
towns ={
'NRB':"Westlands",
'Tka':"Gatundu",
'GRI':"Kimbo",
'KSM':"Lwangni"
}
#adding more towns
towns['NRB'] = 'Kibera'
towns['Tka'] = 'Ruiru'
towns['KKGA'] = 'Miciku'
towns['WBE'] = 'kalaye'
#printing out some counties
print('-' * 10)
print("Nairobi has: " , towns["NRB"])
print("Thika has: " , towns["Tka"])
#printing again
print("Nairobi's abbrevation is" , counties['nairobi'])
print("Thika's abbreviation is" ,counties['Thika'])
print("-" *10)
print("Nairobi has:" , towns[counties['nairobi']] )
print("Thika has:" , towns[counties['Thika']] )
print("-" * 10)
new_dic = {} #created an empty dict to be able to use the counties dict twice?
new_dic = counties.copy()
for county, abbrev in new_dic.items():
print("%s is abbreviated %s" %(county , abbrev))
#print every town in counties
print("-" * 10)
for abbreviation , town in towns.items():
print("%s has the town %s" %(abbreviation , town))
#both at the same time
print("-" * 10)
for counties , abbreviation in counties.items():
print("%r county is abbreviated %r and has towns %r" %(counties , abbreviation
, towns[abbreviation]))
#created an empty dict to be able to use the counties dict for the third time why?
second_dict = {}
second_dict = new_dic.copy()
print("-" * 10)
county = second_dict.get('Macha' )
if not county:
print("sorry there is no Macha")
town = towns.get("Mch" , "Doesnt Exist")
print("the town for the county 'Mch' is: %s" %town)
| false |
aa960deeb474ab57d4ef72d675a8fd4742104014 | egonnelli/algorithms | /sorting_algorithms/01_bubblesort.py | 544 | 4.34375 | 4 | #Bubblesort algorithm in python
#Time complexity - O(N^2)
def bubble_sort(array):
"""
This functions implements the bubble sort algorithm
"""
is_sorted = False
counter = 0
while not is_sorted:
is_sorted = True
for i in range(len(array) - 1 - counter)
if array[i] > array[i+1]:
swap(i, i+1, array)
is_sorted = False
counter += 1
return array
def swap(i,j,array):
array[i] , array[j] = array[j], array[i]
"""
import numpy as np
array = np.array([4,5,6,7,1,2,3])
bubble_sort(array)
#array([1, 2, 3, 4, 5, 6, 7])
""" | true |
4d5b37c3bef7ed5a71b12b3ba30b895af39b6b12 | Dushyanttara/Competitive-Programing | /deli.py | 730 | 4.34375 | 4 | #Dushyant Tara(19-06-2020): This program will help you understand while loop through exercises
sandwich_orders = ['aloo tikki','bbq chicken','ceasers','pastrami', 'tuna','cheese','pastrami','paneer tikka','ham','pastrami']
finished_sandwiches = []
print("The Deli has run out of Pastrami")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print("\nThese are the final orders:")
for sw in sandwich_orders:
print(sw)
while sandwich_orders:
current_sw = sandwich_orders.pop()
finished_sandwiches.append(current_sw)
print("I made you a " + current_sw + " sandwich.")
print("\nThe following sandwiches have been made: ")
for sw in finished_sandwiches:
print("\n"+sw)
| false |
2af5b432ac298bebe3343f9ee18ae79e5f368b3e | Dushyanttara/Competitive-Programing | /aliens.py | 2,312 | 4.15625 | 4 | """#Dushyant Tara(19-06-2020): This program will help you understand dictionary as a data strucutre
alien_0 = {'color': 'green',
'points': 5}
#print(alien_0['color'])
#print(alien_0['points'])
#new_points = alien_0['points']
#print("You just earned " + str(new_points) + " points.")
#Adding new key:value pairs
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#Starting with an empty dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
#Modifying values in a Dictionary
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
alien_0 = {'x_position' : 0, 'y_position': 25, 'speed':'medium'}
print("Original x-position: " + str(alien_0['x_position']))
alien_0['speed'] = 'fast'
#Move the alien to the right
#Determine how far to move the alien based on its speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
#The new position is the old position plus the increment
alien_0['x_position'] += x_increment
print("New x-position: " + str(alien_0['x_position']))
#Removing Key-value pairs
alien_0 = {'color':'green','points':5}
print(alien_0)
del alien_0['points']
print(alien_0)
"""
alien_0 = {'color': 'green', 'points':5}
alien_1 = {'color': 'yellow', 'points':10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
#More aliens
#Make an empty list for storing aliens
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color':'green','points':5, 'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
#Show first 5 aliens
for alien in aliens[:5]:
print(alien)
print("....")
#Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))
| true |
6b6c88029116d4f5de407c8c8640345bdadb10bb | PajamaProgrammer/Python_MIT-6.00_Problem-Set-Solutions | /Problem Set 2/ps2b.py | 2,303 | 4.15625 | 4 | # Problem Set 2 (Part 4)
# Name: Pajama Programmer
# Date: 28-Oct-2015
#
"""
Problem4.
Assume that the variable packages is bound to a tuple of length 3, the values of which specify
the sizes of the packages, ordered from smallest to largest. Write a program that uses
exhaustive search to find the largest number (less than 200) of McNuggets that cannot be bought
in exact quantity. We limit the number to be less than 200 (although this is an arbitrary choice)
because in some cases there is no largest value that cannot be bought in exact quantity, and we
don’t want to search forever. Please use ps2b_template.py to structure your code.
Have your code print out its result in the following format:
“Given package sizes <x>, <y>, and <z>, the largest number of McNuggets that cannot be bought in exact quantity is: <n>”
Test your program on a variety of choices, by changing the value for packages.
Include the case (6,9,20), as well as some other test cases of your own choosing.
"""
bestSoFar = 0 # variable that keeps track of largest number
# of McNuggets that cannot be bought in exact quantity
packages = (9,11,20) # variable that contains package sizes
def PrintNuggetFunction (nuggets, x, y, z):
print ('I want to order Chicken McNuggets in packs of', x, y, 'and', z, 'so that I have exactly', nuggets, 'nuggets')
return
def PrintNuggetSolution (nuggets, x, y, z):
print ('It takes', x, 'packs of 6,', y, 'packs of 9, and', z, 'packs of 20 Chicken McNuggets to =', nuggets)
return
def FindNuggetSolution (nuggets, x, y, z):
for c in range (0, nuggets):
for b in range (0, nuggets):
for a in range (0, nuggets):
if (x*a + y*b + z*c == nuggets):
#PrintNuggetSolution (nuggets, x, y, z)
return 1
return 0
x = packages[0]
y = packages[1]
z = packages[2]
for n in range(1, 200): # only search for solutions up to size 200
if FindNuggetSolution(n, x, y, z) == 0:
counter = 0
bestSoFar = n
else:
counter +=1
#print(counter)
if counter == x:
break
print ('Given package sizes <', x,'>, <', y,'>, and <', z, '>, the largest number of McNuggets that cannot be bought in exact quantity is: ', bestSoFar, sep='')
| true |
2352cc95d3464d4a7f6a7f01781d9de1278b0113 | UddeshJain/Master-Computer-Science | /Data_Structure/Python/Stack.py | 1,262 | 4.34375 | 4 | class Stack(object):
'''
class to represent a stack
Implemented with an array
'''
def __init__(self):
'''
Constructor
'''
self.datas = []
def __str__(self):
return " ".join(str(e) for e in reversed(self.datas))
def size(self):
'''
return the size of the stack
'''
return len(self.datas)
def top(self):
'''
Return the top of the stack
'''
return self.datas[-1]
def push(self, value):
'''
add a value on the stack
'''
return self.datas.append(value)
def pop(self):
'''
pop the last element of the stack
'''
value = self.top()
del self.datas[-1]
return value
def empty(self):
self.datas = []
def print_stack(stack):
print(f'stack : {stack}')
if __name__ == "__main__":
stack = Stack()
print('Pushing 1')
stack.push(1)
print_stack(stack)
print('Pushing 5')
stack.push(5)
print_stack(stack)
print(f'top : {stack.top()}')
print('popping')
print(f'value poped : {stack.pop()}')
print_stack(stack) | true |
e8faa90b2c9b3ee9a1d694bb6a236e80cbd27733 | missystem/math-crypto | /mathfxn.py | 790 | 4.53125 | 5 | """
Authors: Missy Shi
Date: 05/22/2020
Python Version: 3.8.1
Functions:
- largest_prime_factor
Find the largest prime factor of a number
- prime_factors
Given a integer, return a set of factors of the number
"""
import math
def largest_prime_factor(n: int) -> int:
""" Return largest prime factor of number n """
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
return n
def prime_factors(n_1: int) -> set:
""" Return a set of factors of number n_1 """
lpf = largest_prime_factor(n_1)
factors = set()
factors.add(lpf)
c = 16
rest = n_1 // lpf
while (rest != 1):
lpf = largest_prime_factor(rest)
rest = rest // lpf
factors.add(lpf)
c -= 1
return factors | true |
682d25a675d2b58c48c7359774378ae921405b24 | missystem/math-crypto | /prime.py | 1,155 | 4.21875 | 4 | """
Author: Missy Shi
Course: math 458
Date: 04/23/2020
Project: A3 - 1
Description:
Write a Python function which, given n,
returns a list of all the primes less than n.
There should be 25 primes less than 100, for instance.
Task:
How many prime numbers are there which are less than 367400?
"""
import math
def is_prime(n: int) -> bool:
""" Check if a integer is prime,
If it is, return True, else return False """
if n < 2:
# print(f"{n} is not a prime number")
return False
else:
for i in range(2, n):
if (n % i) == 0:
# print(f"{n} is not a prime number")
# print(f"{n} divides {i} = {n//i}")
return False
return True
def q1():
""" Find primes less than given number n """
# n = int(input('Input an integer: '))
n = 367400
pl = []
for i in range(1, n):
if is_prime(i) is True:
pl.append(i)
count = len(pl)
print(f"{count} prime numbers less than {n}")
# print(pl)
return
def main():
"""main program runner"""
q1()
if __name__ == '__main__':
main() | true |
cea5559f924ca0ec895074ca5898c96fc003bc74 | sahilkumar4all/HMRTraining | /Day-5/calc_final.py | 380 | 4.125 | 4 | def calc(operator):
z = eval(x+operator+y)
print(z)
print('''
Press 1 for addition
press 2 for substraction
press 3 for multiplication
press 4 for division''')
x = input("enter first no")
y = input("enter second no")
choice = input("enter operation you wanna perform")
dict = {"1":"+",
"2":"-",
"3":"*",
"4":"/"}
opr = dict.get(choice)
calc(opr)
| true |
cc669352fa7f30b87d40343ab529635289a35884 | Miguelmargar/file-io | /writefile.py | 698 | 4.125 | 4 | f = open("newfile.txt", "a") # opens and creates file called newfile.txt to write on it with "w" - if using "a" it means append not create new or re-write
f.write("\nHello World\n") # writes Hello on the file opened above - depending on where you use the \n the lines will brake accordingly
f.close() # closes the file but it is still stored in memory
#----------------------------------------------------------------------
words = ["the", "quick", "brown", "fox"]
words_as_string = "\n".join(words) # this will append \n to the words in words list above it
f = open("newfile.txt", "w")
f.write(words_as_string)
f.close() | true |
5bfd768ba34df709af7e5c425510b44dc8a63cb0 | cheeseaddict/think-python | /chapter-5/ex-5.3.py | 419 | 4.15625 | 4 | def check_fermat(a, b, c, n):
if a**n + b**n == c**n and n > 2:
print("Holy smokes, Fermat was wrong!")
else:
print("No that does not work")
def input_test_values():
a = int(input("Enter a value for a: "))
b = int(input("Enter a value for b: "))
c = int(input("Enter a value for c: "))
n = int(input("Enter a value for n: "))
check_fermat(a, b, c, n)
input_test_values()
| false |
a153c0f74861ec3c8c786b7b5d9b379331904612 | cheeseaddict/think-python | /chapter-6/exercise-6.2.py | 667 | 4.25 | 4 | import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
print(distance(1,2,4,6))
"""
As an exercise, use incremental development to write a function called hypotenuse that
returns the length of the hypotenuse of a right triangle given the lengths of the other two
legs as arguments. Record each stage of the development process as you go.
"""
def hypotenuse(a, b):
# a**2 + b**2 = c**2
# square_a = a**2
# square_b = b**2
# c = square_a + square_b
# result = math.sqrt(c)
return math.sqrt(a**2 + b**2)
print(hypotenuse(3, 4)) # => 5.0
| true |
3d045213ec7cc8711783ec2e6be8eeedf4ebf6c2 | FrankchingKang/phrasehunter | /phrasehunter/character.py | 1,774 | 4.125 | 4 | # Create your Character class logic in here.
class Character(object):
"""The class should include an initializer or def __init__ that receives a char parameter, which should be a single character string."""
def __init__(self,char):
"""An instance attribute to store the single char string character so the Character object will be able to remember the original character.
You might call this instance attribute original, but that will be up to you.
An instance attribute to store a boolean value (True or False) of whether or not this letter has had a guess attempted against it.
You can initialize this to False inside __init__ as any new Character object will start with a default of False meaning it has not been guessed before.
You might name this instance attribute was_guessed, but that will also be up to you."""
if len(char) == 1:
self.original = char
else:
self.original = char[0]
self.was_guessed = False
def check_the_answer(self,guess):
"""An instance method that will take a single string character guess as an argument when its called.
The job of this instance method is to update the instance attribute storing the boolean value,
if the guess character is an exact match to the instance attribute storing the original char passed in when the Character object was created."""
if guess == self.original:
self.was_guessed = True
return True
else:
return False
def show_the_char(self):
if self.was_guessed:
print(self.original, end = " ")
else:
print("_", end = " ")
def reset_character(self):
self.was_guessed = False
| true |
898ed9b37e512dca37848a040ff175ce57b65e08 | mverleg/bardeen | /bardeen/inout.py | 2,011 | 4.15625 | 4 |
"""
Routines related to text input/output
"""
import sys, os
def clear_stdout(lines = 1, stream = sys.stdout, flush = True):
"""
Uses escape characters to move back number of lines and empty them
To write something on the empty lines, use :func:sys.stdout.write() and :func:sys.stdout.flush()
:param lines: the number of lines to clear
:param stream: by default, stdout is cleared, but this can be replaced by another stream that uses these \
escape characters (stderr comes to mind)
:param flush: by default, uses flush after writing, but canbe overriden if you will do it yourself soon after
"""
stream.write('\033[F\r\x1b[K' * lines)
if flush:
stream.flush()
def reprint(txt, lines = 1, stream = sys.stdout):
"""
Removes lines from stdout and prints the requested text txt instead of them
:param txt: the text you want to print; works best if no more than `lines` lines
:param stream: see ``clear_stdout``
:param lines: the number of lines you want to use; \
this amount is cleared and if txt is shorter, the remainder is prepended
For example for status monitoring:
1. print N newlines
2. do something or check something until there is news
3. use ``reprint`` to print the as most N lines update using lines = N
4. repeat step 2 and 3 until task is done
5. if you want to remove the last status message, call clear_stdout using lines = N
"""
clear_stdout(lines = lines, flush = False)
line_count = len(txt.splitlines())
stream.write(
os.linesep * (lines - line_count) +
txt +
os.linesep
)
stream.flush()
def add_linebreaks(text, max_len=80):
"""
Add linebreaks on whitespace such that no line is longer than `max_len`, unless it contains a single word that's longer.
There are probably way faster methods, but this is simple and works.
"""
br_text = ''
len_cnt = 0
for word in text.split(' '):
len_cnt += len(word) + 1
if len_cnt > max_len:
len_cnt = len(word)
br_text += '\n' + word
else:
br_text += ' ' + word
return br_text[1:]
| true |
c824029a5d1ef7317bb98bd39f623292fd392d71 | ms-shakil/Some_problems_with_solve | /Extra_Long_Factorial.py.py | 401 | 4.125 | 4 | """
The factorial of the integer n , written n! , is defined as:
n! = n * (n-1)*(n-2)*... *2*1
Calculate and print the factorial of a given integer.
For example Inp =25 we calculate 25* 24* 23*....*2*1 and we get 15511210043330985984000000 .
"""
def Factorial(inp):
val = 1
for i in range(1,inp):
val += val*i
print(val)
inp = int(input("Enter the value:"))
Factorial(inp) | true |
12b784aecca1d4276228b7b7ad13d3cc1d679208 | lenncb/safe_password | /main.py | 1,319 | 4.125 | 4 | # This programm will show you how strong your password is
# If your password is weak, program will generate new and strong password.
# Just write your password
import re, password_generator
password = input(str('Enter your password: '))
#good password is if it has minimum 8 signs, inculde small and big letters and has minimum one number
#strong password is if it has minimum 8 signs, inculde small and big letters, minimum one number and one special sign e.g. exclamation mark (!)
good_password = re.compile(r'''
^(?=.*[A-Z])
(?=.*[a-z])
(?=.*\d)
(.{8,})$
''', re.VERBOSE)
strong_password = re.compile(r'''
^(?=.*[A-Z])
(?=.*[a-z])
(?=.*\d)
(?=.*[(){}[@/|:;<>+^$!%*?&'`~])
(.{8,})$
''', re.VERBOSE)
print(strong_password.findall(password))
if len(strong_password.findall(password)) == 1 :
print('Your password: '+ str(''.join(strong_password.findall(password))) + " is strong password. You don't need to change it.")
elif len(good_password.findall(password)) == 1:
print('Your password: '+ str(''.join(good_password.findall(password))) + " is good password. You can change it but you dont need to do it.")
password_generator.new_password_question()
else:
print('Your password: ' + password + " is too weak ! Change it as fast as it is possible !")
password_generator.new_password_question()
| true |
37693a5b038c83a5eae1f13d6bd0540c4852b9ad | navinduJay/interview | /python/sort/insertionSort.py | 635 | 4.34375 | 4 | #INSERTION SORT
array = [] #array declaration
for everyValue in range(10):
array.append(input("Enter number ")) #adding values to the array
print('Unsorted array')
print(array)
def insertionSort(array): #function declaration
for j in range(1 , len(array)): # starting index is 1(2nd position) to array length
keyValue = array[j] #key = array[j]
i = j - 1 #i'th index should one less than j'th index
while(i >= 0 and array[i] > keyValue):
array[i + 1] = array[i]
i = i - 1
array[i + 1] = keyValue
insertionSort(array)
print('Sorted array')
print(array)
| true |
c574d55303bce0e3e99b39777be42153f3c47a7d | minkyaw17/CECS-328 | /Lab 5/lab5.py | 2,656 | 4.15625 | 4 | import random
import time
def swap(arr, a, b): # swap function to be used in the heap sort and selection sort
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def max_heapify(arr, i, n): # parameter n for length of array
max_element = i
left = (2 * i) + 1
right = (2 * i) + 2
max_element = i
# if there's a left child of the root and it's greater than the root
if left < n and arr[left] > arr[max_element]:
max_element = left
# if there's a right child of the root and it's greater than the root
if right < n and arr[right] > arr[max_element]:
max_element = right
if max_element != i:
swap(arr, i, max_element)
max_heapify(arr, max_element, n)
def build_maxHeap(arr):
n = len(arr)
start_range = (n // 2) - 1
for i in range(start_range, -1, -1):
max_heapify(arr, i, n)
def heap_sort(arr, ind, n):
build_maxHeap(arr)
for i in range(n - 1, 0, -1): # removing the roots one by one until the tree/array becomes empty
swap(arr, arr.index(arr[i]), arr.index(arr[0]))
max_heapify(arr, 0, i)
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i # keeping track of the min index
for j in range(i + 1, n):
if arr[min_index] > arr[j]: # if the element with the min index is greater than the current element,
# set it equal to that index
min_index = j
swap(arr, i, min_index)
def heap_sort_program():
print("Part A:\n")
n = int(input("Please enter the number of elements you wish to put into an array (a positive integer): "))
# assuming user input will be 1000 and will do 100 reps to check the run time
a = [random.randint(-100, 100) for i in range(n)]
a2 = a[:]
reps = 100
start_hs = time.time_ns()
for i in range(reps):
heap_sort(a, 0, n)
stop_hs = time.time_ns()
end_hs = (stop_hs - start_hs) / reps
print("Average running time for heap sort:", end_hs, "ns")
start_sc = time.time_ns()
for i in range(reps):
selection_sort(a2)
stop_sc = time.time_ns()
end_sc = (stop_sc - start_sc) / reps
print("Average running time for selection sort:", end_sc, "ns")
time_diff = end_sc - end_hs
print("Time difference in which heapsort is faster by:", time_diff, "ns")
def manual_heap_sort():
print("\nPart B:\n")
size_arr = 10
a = [random.randint(-100, 100) for i in range(size_arr)]
print("Original array:", a)
heap_sort(a, 0, size_arr)
print("Sorted array:", a)
heap_sort_program()
manual_heap_sort()
| true |
589aada2ad71b067e9602780edd62c7e540169db | carlosmertens/Python-Masterclass | /challenge_control_flow.py | 1,456 | 4.34375 | 4 | # Complete Python MasterClass Course
#
# This challenge is intended to practise for loops and if/else statements,
# so although you could use other techniques (such as splitting the string up),
# that's not the approach we're looking for here.
#
# Create a program that takes an IP address entered at the keyboard and prints
# out the number of segments it contains, and the length of each segment.
#
# An IP address consists of 4 numbers, separated with a full stop.
# But your program should count however many are entered since we're just
# interested in the number of segments and how long each one is.
# Examples of the input you may get are:
# 127.0.0.1
# .192.168.0.1
# 10.0.123456.255
# 172.16
# 255
# .123.45.678.91
# 123.4567.8.9.
# 123.156.289.10123456
# 10.10t.10.10
# 12.9.34.6.12.90
# '' - that is, press enter without typing anything
# Retrieve input from user
ip_address = input("Please enter your IP address: ")
# Add a dot at the end if it is none. It ill help with count the iterations
if ip_address[-1] != ".":
ip_address += "."
# Initiate counter variables
segments_number = 1
segment_length = 0
# Iterate throught the input
for i in ip_address:
# Update counter when a dot is encounter
if i == ".":
print("Segment {} contains {} characters.".format(segments_number, segment_length))
segments_number += 1
segment_length = 0
else:
segment_length += 1
| true |
ee6e9248a17fc4ec2426cebf57ec9404dea28955 | ardaunal4/My_Python_Lessons | /ClassPython/example_of_properties_of_classes.py | 1,459 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 27 02:35:30 2020
@author: ardau
"""
from abc import ABC, abstractmethod
from cmath import pi
class shape(ABC):
"""
Parent class / abstract class example
"""
# abstract methods
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
# overriding and polymorphism
def toString(self):
pass
class square(shape):
def __init__(self, edge):
self.__edge = edge # encapsulation or with other mean private attribute
def area(self):
area = self.__edge ** 2
print('Square area = ', area)
def perimeter(self):
perimeter = self.__edge * 4
print('Perimeter of square = ', perimeter)
def toString(self):
print('Square edge = ', self.__edge)
class circle(shape):
def __init__(self, radius):
self.__radius = radius
def area(self):
area = pi * self.__radius ** 2
print('circle area = ', area)
def perimeter(self):
perimeter = 2 * pi * self.__radius
print("perimeter of circle = ", perimeter)
def toString(self):
print('Circle radius = ', self.__radius)
c = circle(5)
c.toString()
c.area()
c.perimeter()
s = square(5)
s.toString()
s.area()
s.perimeter()
| true |
33c1feb36398f075fc0b1d205803ad901e7366d6 | ardaunal4/My_Python_Lessons | /ALGORITHMS/Fundemantals of_Python_Questions/questions3.py | 723 | 4.25 | 4 | # How you can convert a sorted list to random
from random import shuffle
my_list = [0, 1, 2, 3, 4, 5, 6, 7]
print("Sorted list : ", my_list)
shuffle(my_list)
print("Shuffled list : ", my_list)
# How you can make sorted list from random list
my_list.sort()
print("Sorted list : ", my_list)
# What are functionality of the join() and split() functions
astring = "hello"
new_string = ".".join(astring) # it puts . between every latter in the word.
print("Join() with '.' : ", new_string)
splitted_string = new_string.split(".") # Split function seperates the word according to '.'
print("Split() with '.' : ", splitted_string)
joined = "".join(splitted_string)
print("Join() after split() : ", joined)
| true |
5e2eba80e377a1eb7d2fadfe8c52999605fe8e06 | ardaunal4/My_Python_Lessons | /ClassPython/abstract_class.py | 488 | 4.28125 | 4 | from abc import ABC, abstractmethod # abc -> abstract base class
class Animal(ABC): #super class
@abstractmethod # this makes the class abstract
def walk(self):
pass
def run(self):
pass
# this abstract class is a kind of template for other sub classes
class Bird(Animal): # sub class or child class
def __init__(self):
print('bird')
def walk(self):
print('walk')
obj1 = Animal()
# b1 = Bird() | true |
6421bd469e371aa256b634c344f81c71072ff336 | dailycodemode/dailyprogrammer | /Python/034_squareTwoLargest.py | 984 | 4.15625 | 4 | # https://www.reddit.com/r/dailyprogrammer/comments/rmmn8/3312012_challenge_34_easy/
# DAILY CODE MODE
def square_two_largest(list):
list.sort(reverse=True)
return list[0] ** 2 + list[1] ** 2
print(square_two_largest([3,1,2]))
# ANSWER BY Should_I_say_this
def sumsq(a,b,c):
l=[a,b,c]
del l[l.index(min(l))]
return sum(i**2 for i in l)
# BREAKDOWN
# del l[l.index(min(l))]
# Answer has chosen to eliminate the lowest number from the list to be only left with two arguments
sum(i**2 for i in l)
# He then squares everything in the list and then returns the value
# Comment
# Not the greatest fan of the answer provided because it can only ever be used for this scenario where
# three arguments are given and the sum of the two highest is returned.
# With my answer, it doesn't matter the size of the list.
# I should not that I should the questions a little more carefully because it asked for three arguments.
# Not three arguements contained within a list. | true |
575ce16017a9ace610e155825511410519cc0a9c | Bacbia3696/rsa-key-gen | /src/helper.py | 1,937 | 4.21875 | 4 | from random import randrange, getrandbits, seed
def is_prime(n, k=128):
""" Test if a number is a prime use Miller-Rabin algorithm
Args:
n int: number to test
k int: number of test to do
return True if n is prime
"""
if n == 2 or n == 3:
return True
if n <= 1 or n % 2 == 0:
return False
# find r and s
s = 0
r = n - 1
while r & 1 == 0:
s += 1
r //= 2
for _ in range(k):
a = randrange(2, n-1)
x = pow(a, r, n)
if x != 1 and x != n-1:
j = 1
while j < s and x != n-1:
x = pow(x, 2, n)
if x == 1:
return False
j += 1
if x != n-1:
return False
return True
def generate_prime_cadidate(length):
""" Generate an odd integer randomly
Args:
length int: number of bits length
return a integer
"""
p = getrandbits(length)
p |= (1 << length-1) | 1
return p
def generate_prime_number(user_seed, length=1024):
""" Generate a prime
Args:
user_seed: seed use for randomization
length int: length of the prime to generate, int bits (default is 1024)
return a prime number with high properbility
"""
seed(user_seed)
p = generate_prime_cadidate(length)
# keep generating while the primality test fail
while not is_prime(p, 10):
p = generate_prime_cadidate(length)
return p
def extended_gcd(a, b):
""" Find x, y such that ax+by=gcd(a,b)
Args:
a int: first number
b int: second number
return gcd, x, y
"""
xa, ya = 1, 0
xb, yb = 0, 1
while b != 0:
q = a//b
r = a % b
a, b = b, r
xr, yr = xa-q*xb, ya-q*yb
xa, ya = xb, yb
xb, yb = xr, yr
return a, xa, ya
| false |
bdbd2c226ad2c18abcaa9c781d7951357cd1cb0c | Vasilii-Redinskii/ps-pb-hw4 | /collections.py | 490 | 4.125 | 4 | from collections import namedtuple
# Создаем описание (т.е. некую структуру) для объекта
student = namedtuple('student','first_name last_name age')
# Создаем сам объект, используя описание
student1 = student(first_name='Иван', last_name='Иванов', age=18)
# Обращаемся к полям объекта через точку
print(student1.first_name)
print(student1.last_name)
print(student1.age)
| false |
4a977849536b8afc9d7cce8f715d1359009d14da | rnekadi/CSEE5590_PYTHON_DEEPLEARNING_FALL2018 | /ICP3/Source/codon.py | 522 | 4.21875 | 4 | # Program to read DNA Codon Sequence and Split into individual Codon
# Fixed Codon Sequence
codonseq = 'AAAGGGTTTAAA'
# Define List to hold individual Codon
codon = []
# Defining function to to fill Codon list
def codonlist(seq):
if len(seq) % 3 == 0:
for i in range(0, len(seq), 3):
codon.append(seq[i:i+3])
print()
# Calling Codonlist function
codonlist(codonseq)
# Output
print('The input Sequence is ', codonseq)
print('The individual codon sequence are : ', codon)
| true |
2d7a2d740143a19d38e290c3dc81e00cafcdeaff | smailmedjadi/jenkins_blueocean | /src/new_functions.py | 570 | 4.1875 | 4 | def bubbleSort(list):
for passnum in range(len(list)-1,0,-1):
for i in range(passnum):
if list[i]>list[i+1]:
temp = list[i]
list[i] = list[i+1]
list[i+1] = temp
def insertionSort(list):
for index in range(1,len(list)):
currentvalue = list[index]
position = index
while position>0 and list[position-1]>currentvalue:
list[position]=list[position-1]
position = position-1
list[position]=currentvalue
print ("testing functions") | true |
c9c0ac3f7b507c15f40170980db8b16ed03f2601 | EhODavi/curso-python | /exercicios-secao06/exercicio08.py | 362 | 4.25 | 4 | numero = float(input('Informe um número: '))
maior_numero = numero
menor_numero = numero
for i in range(9):
numero = float(input('Informe um número: '))
if numero < menor_numero:
menor_numero = numero
if numero > maior_numero:
maior_numero = numero
print(f'Maior número: {maior_numero}')
print(f'Menor número: {menor_numero}')
| false |
926276604ff778d85b0ef490eb4155277d8660b0 | EhODavi/curso-python | /exercicios-secao06/exercicio45.py | 447 | 4.125 | 4 | while True:
print('1 - Converter de km/h para m/s')
print('2 - Converter de m/s para km/s')
print('3 - Finalizar')
opcao = int(input('\nInforme a opção: '))
if opcao == 3:
break
velocidade = float(input('\nInforme a velocidade: '))
if opcao == 1:
print(f'\n{velocidade} km/h são {velocidade / 3.60} m/s\n')
elif opcao == 2:
print(f'\n{velocidade} m/s são {velocidade * 3.60} km/h\n')
| false |
55d0933225917746cf734f4ae38b7ab9b9362828 | ravi4all/PythonOnlineJan_2021 | /backup/code_3.py | 485 | 4.15625 | 4 | '''
for(int i = 0; i <= 10; i++) {
Logic...
}
'''
'''
start = 0
stop = 10 - 1 = 9
step = +1
'''
for i in range(10):
print(i, end=',')
print("Inside Loop")
print("Bye")
'''
start = 2
stop = 10 - 1 = 9
step = +1
'''
for i in range(2,10):
print(i, end=',')
print("Inside Loop")
print('Bye')
'''
start = 2
stop = 21 - 1 = 20
step = +2
'''
for i in range(2,21,2):
print(i, end=',')
print("Inside Loop")
| false |
0ec2e9f2fcb36f32ae4220b6f35fa96529a2af30 | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/sum_2_binary_numbers_without_converting_to_integer.py | 1,784 | 4.21875 | 4 | # Task:
#
# Given two binary numbers represented as strings, return the sum of the two binary numbers as a new binary represented
# as a string. Do this without converting the whole binary string into an integer.
#
# Here's an example and some starter code.
#
# def sum_binary(bin1, bin2):
# # Fill this in.
#
# print(sum_binary("11101", "1011"))
# # 101000
from typing import Tuple
def sum_binary_digits(binary_digit1: str, binary_digit2: str, overflow: bool) -> Tuple[str, bool]:
if binary_digit1 == '1':
if binary_digit2 == '1':
if overflow:
return '1', True
else:
return '0', True
else:
if overflow:
return '0', True
else:
return '1', False
else:
if binary_digit2 == '1':
if overflow:
return '0', True
else:
return '1', False
else:
if overflow:
return '1', False
else:
return '0', False
def sum_2_binary_numbers_without_converting_to_integer(binary_number1: str, binary_number2: str) -> str:
overflow: bool = False
index_in_number1: int = len(binary_number1) - 1
index_in_number2: int = len(binary_number2) - 1
result: str = ''
while index_in_number1 >= 0 or index_in_number2 >= 0 or overflow:
binary_digit1: str = binary_number1[index_in_number1] if index_in_number1 >= 0 else 0
binary_digit2: str = binary_number2[index_in_number2] if index_in_number2 >= 0 else 0
result_digit, overflow = sum_binary_digits(binary_digit1, binary_digit2, overflow)
result = result_digit + result
index_in_number1 -= 1
index_in_number2 -= 1
return result
| true |
480dd41bb1dfde38741970333c6442df17dd944a | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/sort_array_with_three_values_in_place.py | 2,376 | 4.25 | 4 | # Task:
#
# Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are
# adjacent, with the colors in the order red, white and blue.
#
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
#
# Note: You are not suppose to use the library’s sort function for this problem.
#
# Can you do this in a single pass?
#
# Example:
# Input: [2,0,2,1,1,0]
# Output: [0,0,1,1,2,2]
# Here's a starting point:
#
# class Solution:
# def sortColors(self, nums):
# # Fill this in.
#
# nums = [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1]
# print("Before Sort: ")
# print(nums)
# # [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1]
#
# Solution().sortColors(nums)
# print("After Sort: ")
# print(nums)
# # [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]
from typing import List
class Solution:
@staticmethod
def sort_colors(numbers: List[int]) -> None:
number_count: int = len(numbers)
if number_count > 1:
last_zero_index: int = -1
last_one_index: int = -1
first_two_index: int = number_count
while last_one_index + 1 < first_two_index:
current_number: int = numbers[last_one_index + 1]
if current_number == 0:
last_zero_index += 1
last_one_index += 1
if last_zero_index != last_one_index:
numbers[last_zero_index] = 0
numbers[last_one_index] = 1
elif current_number == 1:
last_one_index += 1
else:
first_two_index -= 1
numbers[last_one_index + 1] = numbers[first_two_index]
numbers[first_two_index] = current_number
def sort_and_print(numbers: List[int]) -> None:
print('Before Sort: {}'.format(numbers))
Solution.sort_colors(numbers)
print('After Sort: {}'.format(numbers), end='\n\n')
sort_and_print([])
# []
sort_and_print([0])
# [0]
sort_and_print([0, 1])
# [0, 1]
sort_and_print([0, 2, 1])
# [0, 2, 1]
sort_and_print([1, 1, 1])
# [1, 1, 1]
sort_and_print([2, 1, 0])
# [0, 1, 2]
sort_and_print([0, 0, 1, 1, 2, 2])
# [0, 0, 1, 1, 2, 2]
sort_and_print([0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1])
# [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2]
| true |
96002e94186bdfef6a04951c5b99d55e21bb9d00 | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/find_first_recurring_character.py | 1,231 | 4.125 | 4 | # Task:
#
# Given a string, return the first recurring letter that appears. If there are no recurring letters, return None.
#
# Example:
#
# Input: qwertty
# Output: t
#
# Input: qwerty
# Output: None
#
# Here's some starter code:
#
# def first_recurring_char(s):
# # Fill this in.
#
# print(first_recurring_char('qwertty'))
# # t
#
# print(first_recurring_char('qwerty'))
# # None
def first_recurring_char(s: str) -> str:
if s is None:
return None
else:
string_length: int = len(s)
if string_length < 2:
return None
else:
previous_character: str = s[0]
for i in range(1, string_length):
current_character: str = s[i]
if current_character == previous_character:
return previous_character
else:
previous_character = current_character
return None
print(first_recurring_char('qwertty'))
# t
print(first_recurring_char('qwerty'))
# None
print(first_recurring_char('qwertyt'))
# None
print(first_recurring_char('qwerttyy'))
# t
print(first_recurring_char('q'))
# None
print(first_recurring_char(''))
# None
print(first_recurring_char(None))
# None
| true |
04269da9800ce546e8c89a5d9cba8b74b102e05d | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/swap_every_two_nodes_in_linked_list.py | 1,632 | 4.15625 | 4 | # Task:
#
# Given a linked list, swap the position of the 1st and 2nd node, then swap the position of the 3rd and 4th node etc.
#
# Here's some starter code:
#
# class Node:
# def __init__(self, value, next=None):
# self.value = value
# self.next = next
#
# def __repr__(self):
# return f"{self.value}, ({self.next.__repr__()})"
#
# def swap_every_two(llist):
# # Fill this in.
#
# llist = Node(1, Node(2, Node(3, Node(4, Node(5)))))
# print(swap_every_two(llist))
# # 2, (1, (4, (3, (5, (None)))))
from typing import Optional
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next: Optional[Node] = next_node
def __repr__(self) -> str:
return f"{self.value}, ({self.next.__repr__()})"
def swap_every_two_nodes_in_linked_list(input_head_node: Optional[Node]) -> Optional[Node]:
head: Optional[Node] = None
previous_already_swapped: Optional[Node] = None
current: Node = input_head_node
while current is not None and current.next is not None:
old_next: Node = current.next
new_current: Node = old_next.next
new_next: Node = current
if previous_already_swapped is not None:
previous_already_swapped.next = old_next
else:
head = old_next
old_next.next = new_next
previous_already_swapped = new_next
new_next.next = None
current = new_current
if current is None:
return head
else:
if head is None:
return current
else:
previous_already_swapped.next = current
return head
| true |
cc2d33ae78495714b158947820c819a25734ed64 | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/find_shortest_distance_of_characters_to_given_character.py | 1,560 | 4.15625 | 4 | # Task:
#
# Given a string s and a character c, find the distance for all characters in the string to the character c in
# the string s. You can assume that the character c will appear at least once in the string.
#
# Here's an example and some starter code:
#
# def shortest_dist(s, c):
# # Fill this in.
#
# print(shortest_dist('helloworld', 'l'))
# # [2, 1, 0, 0, 1, 2, 2, 1, 0, 1]
from typing import List
def calculate_distances_in_one_direction(input_string: str, target_character: str, distances: List[int],
input_range: iter):
distance_to_closest: int = len(input_string)
for i in input_range:
current_character: str = input_string[i]
if current_character == target_character:
distance_to_closest = 0
distances[i] = 0
else:
distance_to_closest += 1
distances[i] = min(distances[i], distance_to_closest)
def find_shortest_distance_of_characters_to_given_character(input_string: str, target_character: str) -> List[int]:
"""Time complexity ... O(n) where *n* is the length of the *input_string*. Reason: we iterate twice over all
characters of *input_string*.
"""
string_length: int = len(input_string)
distances: List[int] = [string_length] * string_length
calculate_distances_in_one_direction(input_string, target_character, distances, range(0, string_length))
calculate_distances_in_one_direction(input_string, target_character, distances, reversed(range(0, string_length)))
return distances
| true |
1dc29418a4324e658afdddbabd372c2dbe9ae97c | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/find_characters_appearing_in_all_strings.py | 862 | 4.15625 | 4 | # Task:
#
# Given a list of strings, find the list of characters that appear in all strings.
#
# Here's an example and some starter code:
#
# def common_characters(strs):
# # Fill this in.
#
# print(common_characters(['google', 'facebook', 'youtube']))
# # ['e', 'o']
from typing import List, Set
def find_characters_appearing_in_all_strings(strings: List[str]) -> Set[str]:
string_count: int = len(strings)
if string_count == 0:
return set()
else:
common_characters: Set[str] = set(strings[0])
for i in range(1, string_count):
new_common_characters: Set[str] = set()
for character in list(strings[i]):
if character in common_characters:
new_common_characters.add(character)
common_characters = new_common_characters
return common_characters
| true |
9e6ca28b0657297cd3223daef3a3fb6eee2e0ec9 | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/reverse_integer_without_converting_it_to_string.py | 677 | 4.3125 | 4 | # Task:
#
# Given an integer, reverse the digits. Do not convert the integer into a string and reverse it.
#
# Here's some examples and some starter code.
#
# def reverse_integer(num):
# # Fill this in.
#
# print(reverse_integer(135))
# # 531
#
# print(reverse_integer(-321))
# # -123
from math import floor
def reverse_integer_without_converting_it_to_string(input_number: int) -> int:
rest: int = input_number
negative: bool = rest < 0
if negative:
rest *= -1
result: int = 0
while rest > 0:
new_rest: int = floor(rest / 10)
result = result * 10 + rest % 10
rest = new_rest
return result * (-1 if negative else 1)
| true |
d720bec8f8a39a08d7eba61fb7006042e54394e8 | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/reverse_binary_representation_of_integer.py | 980 | 4.15625 | 4 | # Task:
#
# Given a 32 bit integer, reverse the bits and return that number.
#
# Example:
#
# Input: 1234
# # In bits this would be 0000 0000 0000 0000 0000 0100 1101 0010
# Output: 1260388352
# # Reversed bits is 0100 1011 0010 0000 0000 0000 0000 0000
#
# Here's some starter code:
#
# def to_bits(n):
# return '{0:08b}'.format(n)
#
# def reverse_num_bits(num):
# # Fill this in.
#
# print(to_bits(1234))
# # 10011010010
# print(reverse_num_bits(1234))
# # 1260388352
# print(to_bits(reverse_num_bits(1234)))
# # 1001011001000000000000000000000
def to_bits(n: int) -> str:
return '{0:b}'.format(n)
def reverse_num_bits(num: int) -> int:
binary_representation: str = '{0:032b}'.format(num)
reversed_binary_representation: str = binary_representation[::-1]
return int(reversed_binary_representation, 2)
print(to_bits(1234))
# 10011010010
print(reverse_num_bits(1234))
# 1260388352
print(to_bits(reverse_num_bits(1234)))
# 1001011001000000000000000000000
| true |
9e1f8ae86d4092c5105f8ab43ff0356c00777fea | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/search_in_matrix_with_sorted_elements.py | 2,075 | 4.25 | 4 | # Task:
#
# Given a matrix that is organized such that the numbers will always be sorted left to right, and the first number of
# each row will always be greater than the last element of the last row (mat[i][0] > mat[i - 1][-1]), search for
# a specific value in the matrix and return whether it exists.
#
# Here's an example and some starter code.
#
# def search_in_matrix_with_sorted_elements(matrix, searched_value):
# # Fill this in.
#
# mat = [
# [1, 3, 5, 8],
# [10, 11, 15, 16],
# [24, 27, 30, 31],
# ]
#
# print(search_in_matrix_with_sorted_elements(mat, 4))
# # False
#
# print(search_in_matrix_with_sorted_elements(mat, 10))
# # True
from math import floor
from typing import List, Tuple
def convert_number_to_matrix_coordinates(number: int, column_count: int) -> Tuple[int, int]:
row_index: int = floor(number / column_count)
column_index: int = number % column_count
return row_index, column_index
def search_in_matrix_with_sorted_elements(matrix: List[List[int]], searched_value: int) -> bool:
"""Time complexity ... O(log n) where *n* is the size of the given matrix. Reason: binary search in matrix
implemented"""
row_count: int = len(matrix)
column_count: int = len(matrix[0])
lower_bound_included: int = 0
upper_bound_excluded: int = row_count * column_count
while lower_bound_included < upper_bound_excluded:
global_index_of_element_in_middle: int = floor((upper_bound_excluded + lower_bound_included) / 2)
row_index_of_element_in_middle, column_index_of_element_in_middle = convert_number_to_matrix_coordinates(
global_index_of_element_in_middle, column_count)
element_in_middle: int = matrix[row_index_of_element_in_middle][column_index_of_element_in_middle]
if element_in_middle == searched_value:
return True
elif element_in_middle > searched_value:
upper_bound_excluded = global_index_of_element_in_middle - 1
else:
lower_bound_included = global_index_of_element_in_middle + 1
return False
| true |
8a5fcc17e24a57d5783b8f91a7a41f480171d9c3 | ksu-is/Hotel-Python | /hotelpython2.py | 1,949 | 4.125 | 4 | print("Welcome to Hotel Python!")
print("\t\t 1 Booking")
print("\t\t 2 Payment")
print("\t\t 3 Guest Requests")
print("\t\t 4 Exit")
reservation=" "
payment=" "
payment_method=" "
requests=" "
def guest_info(reservation="A"):
print("Please collect guest information such as name, phone number, and dates of stay")
reservation=" "
guest_info("A")
agent=input("Enter guest name: ")
print(agent)
agent_a=input("Enter guest phone number: ")
print(agent_a)
agent_b=input("Enter the desired check in date and check out date in MM/DD/YY = MM/DD/YY: ")
print(agent_b)
agent_c=input("Enter cash or card: ")
print(agent_c)
def guest_requests(requests="R"):
print("Ask guest if they have any special requests for the room: ")
requests="R"
guest_requests("R")
agent_d=input("Enter special requests: ")
print(agent_d)
while True:
breakfast = input("Would you like to add breakfast to your stay (yes or no): ")
print()
if breakfast.lower() == "yes":
print("Breakfast will be added to your final bill. This includes breakfast for two. Each additional meal will be $10.")
break
else:
print("Breakfast will not be added to your final bill. Please let me know if you would like to change that.")
room_rate=int(input("Enter weekend room rate: "))
hotel_stayfee=5
breakfast_charge=10
final_total=room_rate + hotel_stayfee + breakfast_charge
print()
print("Repeat the following information back to guest: ")
print()
print("Thank you for choosing to stay at Hotel Python. We have", agent, "staying with us", agent_b, "using", agent_c, "to pay for the room. We also made sure to include", agent_d, "in the room notes as well.")
print()
print("Final Bill as follows...")
print(agent, ",thank you for choosing to stay with us.")
print(agent_a)
print()
print("Method of Payment: ", agent_c)
print("Breakfast Charge: ", breakfast)
print("The total amount charged for your stay is $", final_total)
| true |
ce09f1c9ebded1b1b2716f017583dea3d4cf5a23 | rfaroul/Activities | /Week03/3/lists.py | 1,601 | 4.28125 | 4 | prices = ["24","13","16000","1400"]
price_nums = [int(price) for price in prices]
print(prices)
print(price_nums)
dog = "poodle"
letters = [letter for letter in dog]
print(letters)
print(f"We iterate over a string into a list: {letters}")
capital_letters = [letter.upper() for letter in letters]
print(capital_letters)
#LONG VERSION OF ABOVE
capital_letters2 = []
for letter in letters:
capital_letters2.append(letter.upper())
print(capital_letters2)
no_o = [letter for letter in letters if letter != 'o']
print(no_o)
#or
no_os = []
for letter in letters:
if letter != 'o':
no_os.append(letter)
print(no_os)
june_temperature = [72,65,59,87]
july_temperature = [87,85,92,79]
august_temperature = [88,77,66,100]
temperature = [june_temperature,july_temperature,august_temperature]
lowest_summer_temperatures = [min(temps) for temps in temperature]
print(lowest_summer_temperatures)
#or
lowest_summer_temperatures2 =[]
for temps in temperature:
lowest_summer_temperatures2.append(min(temps))
print(lowest_summer_temperatures2)
print(lowest_summer_temperatures[0])
print(lowest_summer_temperatures[1])
print(lowest_summer_temperatures[2])
print("-" * 50)#divider
print(lowest_summer_temperatures2[0])
print(lowest_summer_temperatures2[1])
print(lowest_summer_temperatures2[2])
print("-" * 50)#divider
#average
print(sum(lowest_summer_temperatures)/len(lowest_summer_temperatures))
def name(parameter):
return "Hello " + parameter
print(name("Kash"))
def avg(data1,data2):
return (sum(data1)/len(data1))+(sum(data2)/len(data2))
print(avg([1,2,3,4,5,6],[3,4,20])) | true |
a9a126c09ea31fd436771775cee74a487a2cd528 | keyasu/30DaysOfPython | /30DaysOfPython/06_days_ Tuples.py | 2,705 | 4.34375 | 4 | print('days-06-Tuples')
"""
元组是有序且不可更改(不可变)的不同数据类型的集合。
元组用圆括号 () 书写。
一旦创建了一个元组,我们就不能改变它的值。
我们不能在元组中使用 add、insert、remove 方法,因为它不可修改(可变)。
与列表不同,元组的方法很少。
与元组相关的方法:
tuple(): 创建一个空元组
count():计算元组中指定项的个数
index():在元组中查找指定项的索引
运算符:连接两个或多个元组并创建一个新元组
"""
# syntax
""" tpl = ('item1', 'item2','item3')
print(tpl)
print(len(tpl))
first_item = tpl[0]
second_item = tpl[1]
print(first_item)
print(second_item) """
""" fruits = ('banana', 'orange', 'mango', 'lemon')
first_fruit = fruits[0]
second_fruit = fruits[1]
last_index =len(fruits) - 1
last_fruit = fruits[last_index]
print(first_fruit)
print(second_fruit)
print(last_fruit)
"""
"""
fruits = ('banana', 'orange', 'mango', 'lemon')
first_fruit = fruits[-4]
second_fruit = fruits[-3]
last_fruit = fruits[-1]
print(first_fruit)
print(second_fruit)
print(last_fruit) """
# 我们可以通过指定一个索引范围来切出一个子元组从哪里开始和在哪里结束,返回值将是一个具有指定项的新元组。
# # Syntax
# tpl = ('item1', 'item2', 'item3','item4')
# all_items = tpl[0:4] # all items
# all_items = tpl[0:] # all items
# middle_two_items = tpl[-3:-1] # does not include item at index 3
# print(all_items)
# print(middle_two_items)
# 我们可以将元组更改为列表,将列表更改为元组。元组是不可变的,如果我们想修改一个元组,我们应该把它改成一个列表。
# fruits = ('banana', 'orange', 'mango', 'lemon')
# fruits = list(fruits)
# fruits[0] = 'apple'
# print(fruits) # ['apple', 'orange', 'mango', 'lemon']
# fruits = tuple(fruits)
# print(fruits) # ('apple', 'orange', 'mango', 'lemon')
# # 我们可以使用in检查列表中是否存在项目,它返回一个布尔值。
# fruits = ('banana', 'orange', 'mango', 'lemon')
# print('orange' in fruits) # True
# print('apple' in fruits) # False
# fruits[0] = 'apple' # TypeError: 'tuple' object does not support item assignment
# # 我们可以使用 + 运算符连接两个或多个元组
# fruits = ('banana', 'orange', 'mango', 'lemon')
# vegetables = ('Tomato', 'Potato', 'Cabbage','Onion', 'Carrot')
# fruits_and_vegetables = fruits + vegetables
# print(fruits_and_vegetables)
# 不可能删除元组中的单个项目,但可以使用del删除元组本身。
fruits = ('banana', 'orange', 'mango', 'lemon')
print(fruits)
del fruits
print(fruits)
| false |
8c3e51f656c307af2f1167dc1fa0d0f907b27d2c | guillempuigcomerma/Exercise.github.io | /goldenspear-backend/caesarEncrypt.py | 711 | 4.375 | 4 | import sys
def caesarEncrypt(text,s):
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
result = ""
text = text.lower()
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if char == ' ':
result+=char
elif (char not in alphabet):
result += char
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
if __name__ =='__main__' :
caesarEncrypt = caesarEncrypt(sys.argv[1],int(sys.argv[2]))
print(caesarEncrypt)
| false |
821f9a0d094f177d3a7b2c2cbf8ed3fee0967e3e | Jayden-Liang/mypractice | /Algorithem/栈和队列/stack.py | 568 | 4.28125 | 4 |
# 因为Stack是存和取最后位置的数据
# 非常简单,就是利用list的append, remove, 和索引查询,
class Stack(object):
def __init__(self):
self.data = []
self.size = 0
def add(self, data):
self.data.append(data)
self.size +=1
def pop(self):
self.data.remove(self.data[-1])
self.size -=1
def peek(self):
print(self.data[-1])
def show(self):
print(self.size)
print(self.data)
a= Stack()
a.add(1)
a.add(2)
a.show()
a.peek()
a.pop()
a.show()
| false |
131f1147267852294f9674c7b6883c1f5f580d7d | minhazalam/py | /data_collectn_and_processing/week_1/nested_iteration.py | 443 | 4.5 | 4 | # In this program we'll implement the nested iteration concepts using
# * two for loops
# * one loop and a square bracket(indexing)
# * indexing(square bracket) and a for loop
# nested list
nested1 = [1, 2, ['a', 'b', 'c'],['d', 'e'],['f', 'g', 'h']]
# iterate
for x in nested1:
# outer loop
print("level1: ")
if type(x) is list :
for y in x :
print(" level2: {}".format(y))
else :
print(x)
| true |
4448b46aeb6c9ba1ea874f52aa7a0a8a10c761d7 | minhazalam/py | /class_inheritance/inheritance/inheritance.py | 827 | 4.28125 | 4 | # Intro : Inheritance in python 3
# current year
CURRENT_YEAR = 2020
# base class
class Person:
# constructor
def __init__(self, name, year_born):
self.name= name
self.year_born = year_born
# def methods
def get_age(self):
return CURRENT_YEAR - self.year_born
# def __str__(self):
# return self.name
# inheritance syntax
# class derived_class(base_class)
# use inheritance to derive properties of the base class
class Student (Person):
# constructor
def __init__(self):
# derive from the person class
Person.__init__(self, name, year_born)
self.knowledge = 0
# def method
def study(self):
return self.knowledge + 1
# create instance
minhaz = Person("Minhaz Alam", 1997)
# print(minhaz.study())
print(minhaz.get_age())
| true |
328931edeb4128727316cc80b135935d06434f6a | minhazalam/py | /py dict fun and files/programs/csv_writing.py | 713 | 4.1875 | 4 | # ABOUT : This program deals with the writing of the .csv files using
# python 3 code as shown
olympians = [("John Aalberg", 31, "Cross Country Skiing"),
("Minna Maarit Aalto", 30, "Sailing"),
("Win Valdemar Aaltonen", 54, "Art Competitions"),
("Wakako Abe", 18, "Cycling")]
out_file = open("reduced_olympics.csv", "w")
# output the header row
out_file.write('Name, Age, Sport')
out_file.write('\n')
# output each row of the file
for olympian in olympians :
row_string = '{}, {}, {}'.format(olympians[0], olympians[1], olympians[2])
#row_string = ','.join([olympians[0], olympians[1], olympians[2]])
out_file.write(row_string)
out_file.write('\n')
#print(out_file)
out_file.close() | false |
b2677a1cee82e3f2a851f604804f276131f63d75 | minhazalam/py | /class_inheritance/exceptions/try_exception.py | 554 | 4.15625 | 4 | # we'll see how this try and exception works in the python 3 programming language
# syntax :
# try:
# <try clause code block>
# except <ErrorType>:
# <exception handler code block>
# def square(num):
# return num * num
# # assertion testingg
# assert square(3) == 9
# try and except block of statement
a_list = ['a', 'b']
try :
# if something went wrong then in try block next statement will not be executed
third = a_list[2]
except:
print("Third element does not exist")
# after except statements are executed
print("heyo") | true |
eff579a5e13bd543666069b222ade3a0d386ba8c | XanderCalvert/learning_python | /bmielse.py | 502 | 4.375 | 4 | height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
_bmi = weight / (height * height)
bmi = round(_bmi, 1)
if bmi <= 18.5:
print(f"Your BMI is {bmi} you are underweight")
elif bmi <= 25:
print(f"Your BMI is {bmi} you are a normal weight")
elif bmi <= 30:
print(f"Your BMI is {bmi} you are slightly overweight")
elif bmi <= 35:
print(f"Your BMI is {bmi} you are obese")
else:
print(f"Your BMI is {bmi} you are clinically obese")
| false |
8c44c1692f9091b3290f50c23ee3529888b606db | adam-worley/com404 | /1-basics/5-functions/4-loop/bot.py | 271 | 4.125 | 4 | def cross_bridge (steps):
x = 0
while (steps>0):
print("Crossed step")
steps = (steps-1)
x = x+1
if (x>=5):
print("The bridge is collapsing!")
else:
print("we must keep going")
cross_bridge(3)
cross_bridge(6)
| true |
0a7343306387e4f6c326a8bec187da13dc2c45ed | adam-worley/com404 | /1-basics/6-mocktca/1-minimumtca/Q2.py | 255 | 4.125 | 4 | print("Where is Forky?")
forky_location=str(input())
if (forky_location=="With Bonnie"):
print("Phew! Bonnie will be happy.")
elif(forky_location=="Running away"):
print ("Oh no! Bonnie will be upset!")
else:
print("Ah! I better look for him") | true |
637abb15832ba8ebafa8e90d958df4ea05d3b236 | keshavkummari/KT_PYTHON_6AM_June19 | /Functions/Overview_Of_Functions.py | 1,347 | 4.25 | 4 | # Functions in Python
# 1. def
# 2. Function Name
# 3. Open & Close Paranthesis and Parameters
# 4. Colon : Suit
# 5. Indented
# 6. return statement - Exits a Function
"""
def function_name(parameters):
function_suite
return [expression]
def sum(var1,var2):
total = var1 + var2
print(total)
return
a = sum(10,20)
#print(a)
"""
# Function Arguments:
'''
You can call a function by using the following types of formal arguments:
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
# 1. Required arguments
def sum(var1):
print(var1)
return
# Create a Variable
abc = 10
a = sum(abc)
sum(abc)
# 2. Keyword arguments
def hello1(name,age):
print(name)
print(age)
return
hello1(name="Guido Van Rossum",age=50)
# 3. Default arguments
#!/usr/bin/python
# Function definition is here
def info( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call info function
info(name="Guido",age=input("Enter the Age: "))
'''
# 4. Variable-length arguments
def info(*var1):
for i in var1:
print(i)
return
info(10,20,30,40,50,60,70,80,90)
# An Asterisk * is placed before the variable/argument name,
# * holds the values of all the non-keyword variable arguments.
| true |
cfbba32a8f869a1f9afaba9381382611f70c789a | MompuPupu/ProjectEuler | /Problems 1 - 10/Problem 1.py | 516 | 4.5 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def determine_if_multiple_of_3_or_5(number):
"""Return whether the number is a multiple of 3 or 5.
"""
if number % 3 == 0 or number % 5 == 0:
return True
else:
return False
if __name__ == '__main__':
total = 0
for i in range(1, 1000):
if determine_if_multiple_of_3_or_5(i):
total = total + i
print(total)
| true |
ffd4583fc2f7498e36d5f9bd8fa7162c08295439 | MompuPupu/ProjectEuler | /Problems 1 - 10/Problem 4.py | 1,154 | 4.34375 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers
# is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
import math
def check_for_palindrome(num):
# loads the number into an array of characters
digit_list = [int(x) for x in str(num)]
# iterates through the array, checking if the first is the same as the last, etc.
for i in range(1, math.floor(len(digit_list) / 2) + 1):
if digit_list[i - 1] != digit_list[-i]:
return False
print(digit_list)
return True
def check_if_multiple_of_three_digits(num):
for i in range(999, 99, -1):
if num % i == 0:
other_factor = num / i
if other_factor > 99 and other_factor < 1000:
return True
return False
if __name__ == "__main__":
test_number = 998001
solution_found = False
# 100 * 100 to 999 * 999 = 10,000 to 998,001
while not solution_found:
if check_for_palindrome(test_number):
if check_if_multiple_of_three_digits(test_number):
solution = test_number
solution_found = True
else:
test_number -= 1
else:
test_number -= 1
print(solution)
| true |
ee164fea12b17eb34cf532481c77e93bd91a2313 | nda11/CS0008-f2016 | /ch5/ch5,ex3.py | 1,064 | 4.375 | 4 | # name : Nabil Alhassani
# email : nda11@pitt.edu
# date :septemper/11th
# class : CS0008-f2016
# instructor : Max Novelli (man8@pitt.edu)
# Description:Starting with Python, Chapter 2,
# Notes:
# any notes to the instructor and/or TA goes here
# ...and now let's program with Python
# exercise 3
# Many financial experts advise that property owners should insure
# their homes or buildings for at least 80 percent of the amount
# it would cost to replace the structure. Write a program that
# asks the user to enter the replacement cost of a building and
# then displays the minimum amount of insurance he or she should
# buy for the property.
def main():
# Ask for the replacement cost of the insured building.
replacement_cost = input('Enter the replacement cost of the building: ')
replace(replacement_cost)
def replace(replacement_cost):
# Find what 80% of the value is.
insurance_value = replacement_cost * 0.8
# State what the minimum insurance needed is.
print 'The minimum amount of insurance you need is $%.2f' % insurance_value, ' dollars.'
main()
| true |
81d1b25c60fd7043a49fb43f2cb4c808c4d21a86 | nda11/CS0008-f2016 | /ch2.py/ch2-ex3 bis.py | 442 | 4.25 | 4 |
# Exercise : ch2-ex3
#This program asks the user to enter the total square meters of land and calculates the number of
#acres in the tract.
#set one_acre value and
one_acre= 4,046.8564224**2
one_square_meter= 0.000247105
#input square_meter
square_meter=float(input('enter the total square meters:',))
# calculation the acre in the tract.
acre=square_meter * one_square_meter
# Display the total acre
print("this is the total acre:",acre)
| true |
935e0d1a4a7f85d3aa7a44c03171faa99c491d6f | marcoahansen/Python-Estudos | /exercicios/semana3/fizz.py | 210 | 4.125 | 4 | def main():
numero= float(input("Digite um número para saber se é divisível por 3:"))
resto3 = numero % 3
if(resto3 == 0):
print("Fizz")
else:
print(int(numero))
main() | false |
2f3cf52da18ad63dcd6a9cec6710b3b1b15f1e9f | Victor-Bonnin/git-tutorial-rattrapages | /guessing_game.py | 1,300 | 4.375 | 4 | #! /usr/bin/python3
# The random package is needed to choose a random number
import random
# Define the game in a function
def guess_loop():
# This is the number the user will have to guess, chosen randomly in between 1 and 100
number_to_guess = random.randint(1, 100)
name = input("Write your name: ")
print("I have in mind a number in between 1 and 100, can you find it?")
# Replay the question until the user finds the correct number
while True:
try:
# Read the number the user inputs
guess = int(input())
# Compare it to the number to guess
if guess > number_to_guess:
print("The number to guess is lower")
elif guess < number_to_guess:
print("The number to guess is higher")
else:
# The user found the number to guess, let's exit
print("You just found the number, it was indeed", guess)
print("You won, well done", name )
return
# A ValueError is raised by the int() function if the user inputs something else than a number
except ValueError as err:
print("Invalid input, please enter an integer")
# Launch the game
guess_loop()
| true |
3759e1450a801809bb2b00bcbf17d8ab474054a4 | nagalr/algo_practice | /src/main/Python/Sort/insertion_sort.py | 565 | 4.15625 | 4 | def insertion_sort(l):
"""
Insertion Sort Implementation.
Time O(n^2) run.
O(1) space complexity.
:param l: List
:return: None, orders in place.
"""
# finds the next item to insert
for i in range(1, len(l)):
if l[i] < l[i - 1]:
item = l[i]
# moves the item to its right location
for j in range(i, 0, -1):
if item < l[j - 1]:
l[j], l[j - 1] = l[j - 1], l[j]
l = [2, 1, 1, -10, 10, -1, 0, 11, -1, 111, -111, -1, 0, 1000]
insertion_sort(l)
print(l)
| true |
15e3ed05dc5919e6a86fe26cd62e6fff05e65209 | wulfebw/algorithms | /scripts/probability_statistics/biased_random.py | 2,057 | 4.25 | 4 | """
:keywords: probability, biased, random
"""
import random
def biased_random(p=.1):
"""
:description: returns 1 with p probability and 0 o/w
"""
if random.random() < p:
return 1
return 0
def unbiased_random():
"""
:description: uses a biased random sampling with unknown bias to achieve an unbiased sampling
:time: average case O(1/(p * (1-p))) - the probability that the while loop stops is the same as the probability that one variable is 0 and the other 1. This is equal to p * (1-p). So the expected run time is the number of coin flips with heads probability p * (1-p) until you get a heads. This is the binomial distribution with expected value 1/probability heads, which in this case is 1/(.1 * .9) = 1/.09 = 11.1.
Which is actually wrong, it should be either p(1-p) or (1-p)p, doubling the probability of leaving the loop, therefore this should be O(2/(p * (1-p))), which actually should be O(1/p)
:space: O(1)
"""
x = y = 0
counter = 0
while x == y:
counter += 1
x = biased_random()
y = biased_random()
return x, counter
if __name__ == '__main__':
runs = 10000
total = 0
total_counter = 0
for i in range(runs):
cur_total, cur_counter = unbiased_random()
total += cur_total
total_counter += cur_counter
avg = total / float(runs)
avg_counter = total_counter / float(runs)
print 'average value and counter after {} runs: {}\t counter: {}'.format(runs, avg, avg_counter)
"""
:additional notes: to get an unbiased estimator from a biased estimator, or generally to undue some sampling bias, find two secondary random variables that combine earlier ones and then decide between them equally
- how do you decide between them equally?
- so event a is you flip two coins, one is heads the other is tails
- event b is you flip two coins one is tails the other is heads
- now just decide between these two equally by randomly choosing the first coin when the two coins are different
""" | true |
914c9007a4dbf898d7d84bcdf477dc00b5a43d89 | JingYiTeo/Python-Practical-2 | /Q08_top2_scores.py | 567 | 4.15625 | 4 | NStudents = int(input("Please Enter Number of Students: "))
Names = []
Scores = []
for i in range(NStudents):
Name = str(input("Please enter Name: "))
Score = int(input("Please enter Score: "))
Names.append(Name)
Scores.append(Score)
Scores, Names = (list(t) for t in zip(*sorted(zip(Scores, Names))))
print("{} with {} marks has the highest score.\n {} with {} marks has the second highest score.".format(Names[len(Names)-1], Scores[len(Scores)-1], Names[len(Names)-2], Scores[len(Scores)-2]))
| true |
ab7a5601210b13fd049b859d96aa0e25c1f6df0e | Soreasan/Python | /MoreList.py | 1,135 | 4.4375 | 4 | #!/usr/bin/env python3
#We can create a list from a string using the split() method
w = "the quick brown fox jumps over the lazy dog".split()
print(w)
#We can search for a value like this which returns the index it's at
i = w.index('fox')
print(i)
print(w[i])
#w.index('unicorn') #Error
#You can check for membership with the 'in' and 'not in' keywords
print(37 in [1, 78, 9, 37, 34, 53])
print(78 not in [1, 78, 9, 37, 34, 53])
#Create a new list
u = "jackdaws love my big sphinx of quarts".split()
print(u)
#We can delete from a list by index
del u[3]
print(u)
#We can also delete from a list by value
u.remove('jackdaws')
print(u)
#Trying to delete an item that isn't there causes a ValueError
#u.remove('pyramid')
#New list...
a = "I accidentally the whole universe".split()
print(a)
#We can insert by index
a.insert(2, "destroyed")
print(a)
#we can combine the list into a word again using a space join operator
words = ' '.join(a)
print(words)
#You can concatenate a list with the following syntaxes:
m = [2, 1, 3]
print(m)
n = [4, 7, 11]
print(n)
k = m + n
print(k)
k += [18, 29, 47]
print(k)
k.extend([76, 129, 199])
print(k)
| true |
e6b4587b69e39a7e1bdbeb7befc1cd064ef1cb35 | Ankitpahuja/LearnPython3.6 | /Lab Assignments/Lab06 - Comprehensions,Zip/Q1.py | 886 | 4.75 | 5 | # Create a text file containing lot of numbers in float form. The numbers may be on separate lines and there may be several numbers on same line as well. We have to read this file, and generate a list by comprehension that contains all the float values as elements. After the data has been loaded, display the total number of values and the maximum/minimum and average values.
#Next is a multi-line comment.
#Step1: Write your logic
"""fp = open("float.txt","r")
for line in fp:
print(line)"""
#Step2: Reducing the lines (removing objects and calling them directly as;)
""" for line in open("float.txt"):
print(line) """
#Step3: Writing the comprehension!
L = [float(line) for line in open("float.txt","r")]
print(len(L))
print("Maximum value is: ",max(L))
print("Minimum value is: ",min(L))
print("Average is: ",sum(L)/len(L))
# End of the Program!
| true |
6486f929c5adccc0980dc26db652e9358c001754 | Ankitpahuja/LearnPython3.6 | /Lab Assignments/Lab05 - RegEX/ppt_assignment.py | 673 | 4.3125 | 4 | '''
Write a function that would validate an enrolment number.
valid=validateEnrolment(eno )
Example enrolment number U101113FCS498
U-1011-13-F-CS-498
13 – is the year of registration, can be between 00 to 99
CS, EC or BT
Last 3 are digits
'''
import re
pattern = re.compile("U1011[0-9][0-9]F(CS|BT)\d\d\d")
def enroll(eno):
found = pattern.search(eno)
if found:
return True
else:
return False
# Main Program Proceeds
eno = input("Enter Enrollment number: (I will tell if it exists or not!)\n")
n = enroll(eno)
if n:
print("Yes, It's a valid E NO. and it exists!")
else:
print("No. Isn't a valid E No.")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.