blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5def1bd799b63e16e9fe067bece1fa9b3d35141d | mikeodf/Python_Line_Shape_Color | /ch2_prog_9_rounded_rectangle_1.py | 2,454 | 4.28125 | 4 | """ ch2 No.9
Program name: rounded_rectangle_1.py
Objective: Draw a rounded rectangle using similar specifications to
a conventionl rectangle. The radius of the corners also needs to be stated.
Keywords: arc circle, rounded rectangle.
============================================================================79
Comments: It is tricky to get each of the 34 coordinate values corrrect
and ways of progressive error correction should be part of the code
writing/testing process.
Tested on: Python 2.6, Python 2.7.3, Python 3.2.3
Author: Mike Ohlson de Fine
"""
from Tkinter import *
#from tkinter import * # For Python 3.2.3 and higher.
root = Tk()
root.title('Rounded rectangle')
cw = 260 # canvas width
ch = 260 # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="white")
canvas_1.grid(row=0, column=1)
start_x = 50
start_y = 200
end_x = 200
end_y = 50
Radius = 40
len1 = end_x - start_x - 2*Radius
len2 = start_y - end_y - 2*Radius
pt1 = start_x, start_y - Radius
pt2 = start_x, start_y - Radius - len2
pt3 = start_x + Radius, end_y
pt4 = start_x + Radius + len1, end_y
pt5 = end_x, end_y + Radius
pt6 = end_x, start_y - Radius
pt7 = end_x - Radius, start_y
pt8 = start_x + Radius, start_y
arc2 = pt2[0], pt2[1] + Radius
arc3 = pt3[0] + Radius, pt3[1]
arc4 = pt4[0] - Radius, pt4[1] + 2 *Radius
arc5 = pt5[0] , pt5[1] - Radius
arc6 = pt6[0] , pt6[1] - Radius
arc7 = pt7[0]- Radius, pt7[1]
arc8 = pt8[0] + Radius, pt8[1]
arc1 = pt1[0] , pt1[1] - Radius
canvas_1.create_line(pt1, pt2, fill="darkblue", width = 4)
canvas_1.create_line(pt3, pt4, fill="darkblue", width = 4)
canvas_1.create_line(pt5, pt6, fill="darkblue", width = 4)
canvas_1.create_line(pt7, pt8, fill="darkblue", width = 4)
canvas_1.create_arc(arc2, arc3, start=90, extent=90, outline="darkblue", width=4)
canvas_1.create_arc(arc4, arc5, start=0, extent=90, outline="darkblue", width=4)
canvas_1.create_arc(arc6, arc7, start=270, extent=90, outline="darkblue", width=4)
canvas_1.create_arc(arc8, arc1, start=-90, extent=-90, outline="darkblue", width=4)
canvas_1.create_rectangle(arc8, arc1, outline="red")
root.mainloop()
| true |
41da0cf9ef8c68bbdc2f84dfb3d24989f04dd417 | parhamafsharnia/AI_search_algorithms_Maze | /Cell.py | 663 | 4.3125 | 4 | class Cell:
"""A cell in the maze.
A maze "Cell" is a point in the grid which may be surrounded by walls to
the north, east, south or west.
"""
def __init__(self, point, n: bool = True, e: bool = True, s: bool = True, w: bool = True):
"""Initialize the cell at (x,y). At first it is surrounded by walls."""
self.n, self.e, self.s, self.w = n, e, s, w
self.visited: bool = False
self.pos = point
self.cost = 0
self.parent = None
def setter(self, n: bool = True, e: bool = True, s: bool = True, w: bool = True):
self.n = n
self.e = e
self.s = s
self.w = w
| true |
28fbd5de71b5a0d4d483fb6ec95022a993f67b63 | vikanksha/Python-Book-Exercises | /condition_loops_program/median.py | 229 | 4.375 | 4 | # Write a Python program to find the median of three values.
val1 = int(input('Enter value 1:'))
val2 = int(input('Enter value 2:'))
val3 = int(input('Enter value 3:'))
if val1 < val2 and val2 < val3:
print('median is', val2) | true |
884e4a7f77c0482425607c3ce1d4fa1e627213d6 | vikanksha/Python-Book-Exercises | /devu_program/list_name.py | 249 | 4.28125 | 4 | # Write a program to return a list of all the names before a specified name.
list_of_names = eval(input(" "))
speci_name = input(" ")
list = []
for i in list_of_names:
if i == speci_name:
break
list_of_names.append(i)
print(list) | true |
e40638d4b9cec1d2f668f3a1a32870e0fd315e36 | vikanksha/Python-Book-Exercises | /chap3/ex1.py | 406 | 4.25 | 4 | # temp conversion
choice = eval(input("Enter selection"))
while choice !="F" and choice != "C":
temp = int(input("enter temp to convert"))
if choice == "F":
converted_temp = (temp-32)*5/9
print(temp , "degree fahrenheit is equal to" , converted_temp, "degree celcius")
else:
converted_temp = (9/5*temp)+32
print(temp , "degree celcius is equal to" , converted_temp, "degree fahrenheit") | true |
2d087f0ac71902d13bcb45ec60dd6fb67108e7da | vikanksha/Python-Book-Exercises | /condition_loops_program/days_no.py | 510 | 4.46875 | 4 | # Write a Python program to convert month name to a number of days.
print("list of month : January, February, March, April, May, June, July, August, September, October, November, December")
Month = input("Enter month name :")
if Month == "Februrary":
print("no of days 28/29")
elif Month in ("January" , "March", "May", "July", "August", "November" , "December"):
print("no of days 31")
elif Month in ("April","June", "September" , "October"):
print("no of days 30")
else:
print("wrong month") | true |
c12d509b78482c34fe24ffbecc37364adb0e7883 | vikanksha/Python-Book-Exercises | /devu_program/t4.py | 343 | 4.1875 | 4 | # 4. write a definition of a method COUNTDOWN(PLACES) to find and display those place names, in which there are more than 5 characters.
# ['DELHI', 'LONDON', 'PARIS', 'NEW YORK', 'DUBAI']
def countdown(places):
for p in places:
if len(p) > 5:
print(p)
print(countdown(['DELHI', 'LONDON', 'PARIS', 'NEW YORK', 'DUBAI'])) | false |
453ca9c00317b80931d41df787587320c5d616e4 | ZohanHo/PycharmProjectsZohan | /untitled3/Задача 10.py | 561 | 4.1875 | 4 | """В математике функция sign(x) (знак числа) определена так:
sign(x) = 1, если x > 0,
sign(x) = -1, если x < 0,
sign(x) = 0, если x = 0.
Для данного числа x выведите значение sign(x).
Эту задачу желательно решить с использованием каскадных инструкций if... elif... else."""
x = int(input("введите x: "))
if x > 0:
print("1")
elif x < 0:
print("-1")
else:
x = 0
print("0")
| false |
6b59d6be3f0e4ba1be591d40f7bd5c4a645064c3 | ZohanHo/PycharmProjectsZohan | /untitled3/Задача 5.py | 329 | 4.125 | 4 | """Условие «Hello, Harry!»
Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания по образцу:"""
z = str(input("Введите имя: "))
print("Hello " + z + "!") | false |
5e1c459f721bfc9c0084f9102d265333113f6f5e | GeekBM/python_hometask | /lesson_3/4.py | 427 | 4.1875 | 4 | x = abs(float(input('Введите действительное положительное число х ')))
y = int(input("Введите целое отрицательное число у "))
while y >= 0:
y = int(input('Вы ввели не отрицательное число. Введите целое отрицательное число у '))
def my_func (x, y):
return x ** y
print(my_func (x, y))
| false |
2793480aa76bb6f501a940ab321ce9c18d182579 | af0262/week9 | /bubble_sort2.py | 627 | 4.375 | 4 | import random
def sort(items):
# 1. TO DO: Implement a "bubble sort" routine here
for outer in range(len(items)):
for inner in range(len(items)-1-outer):
if items[inner] > items[inner+1]:
items[inner], items[inner+1] = items[inner+1], items[inner] # Swap!
return items
numbers = list(range(10))
random.shuffle(numbers)
assert list(range(10)) == sort(numbers)
print("The list was sorted correctly!")
# 2. Change this print statement to display the complexity category.
# Refer to the cheat sheet in week9-class for examples.
print("This algorithm is classified as: O(n^2)")
| true |
9d6fe91d37141db9f013eb58c4b971eebc4714c3 | IghnatenkoMatvey/ip-Ignatenko-Matvey-1 | /lesson2/PythonClass 2.py | 1,281 | 4.125 | 4 | # >
# <
# ==
# !=
# <=
# >=
# x = 5 > 10
# type(x)
# print(x)
# x = 1
# print(x)
# x = True
# if x == 1 or x:
# print('yes')
# elif x:
# print('Noway')
# else:
# print('No')
#
# original_password = 'x777'
# password = input('Введите пароль: ')
# access = 0
# if password == original_password:
# print('Пароль принят, добро пожаловать в систему')
# access = 1
# else:
# print('Пароль неверен, вход запрещен')
# color = 'red'
# if color == 'blue':
# print('Синий')
# elif color == 'red':
# print('Красный')
# elif color == 'green':
# print('Зеленый')
# else:
# print('Неизвестный цвет')
# a = 0
# while a < 7:
# print('A')
# a += 1
# x = input(' Say yes or no: ')
# while x == 'yes':
# x=input(' Say yes or no: ')
# print('Yeeees')
# a = 0
# while a >=0:
# if a == 7:
# break
# a +=1
# print('A')
# a = -1
# while a < 10:
# a += 1
# if a == 7 or a % 2 == 1:
# continue
# print('a --', a)
# a = 5
# while a > 0:
# print("!")
# a = a+1
# word_str = "Hello, world!"
# for l in word_str:
# print(l)
# lst = [1, 3, 5, 7, 9]
# for i in lst:
# print(i**2)
| false |
7551611f9a88fd54b427b21bb02f02cbb7e12f6a | payal8797/Algo | /bubble.py | 472 | 4.28125 | 4 | def bubble(array):
array=[]
n=int(input("Enter number of elements:"))
for s in range(n):
m=int(input())
array.append(m)
print("Elements are:",array)
for i in range(n):
for j in range(n-i-1):
if(array[j]>array[j+1]):
array[j],array[j+1]=array[j+1],array[j]
print("Sorted array is:")
for i in range(n):
print("%d" %array[i])
if __name__=="__main__":
array=[]
bubble(array) | false |
50741e2a960c9bc0158f8c32819083126e4928bc | nikiknak/fundamentos_de_informatica | /ejercicios guia 1/ej5 G1.py | 276 | 4.1875 | 4 | #5: Realizar un programa que lea tres números por teclado y calcule el promedio de ellos.
num1 = int(input("ingrese un número:"))
num2 = int(input("ingrese otro numero:"))
num3 = int(input("ingrese otro numero:"))
promedio = (num1 + num2 + num3) / 3
print(int(promedio))
| false |
796cb0250390e87782d2422d475f2914fd093804 | nikiknak/fundamentos_de_informatica | /Segunda parte /guia Pandas 2/ej5.py | 348 | 4.125 | 4 | #Ejercicio 5
#Realizá un programa que verifique si una columna dada se encuentra presente en un DataFrame.
import pandas as pd
datos = {"A": [1,2,3,4], "B": [5,6,7,8], "C": [9,10,11,12]}
df=pd.DataFrame(data=datos, index=["w","x","y","z"])
print(df)
verifique = "A" in df.columns
print(verifique)
verifique2 = "a" in df.columns
print(verifique2)
| false |
87d299f0568c4c3e0b949af5a542e9d8d6a2ffd9 | juandaangarita/CursoBasicoPython | /multiplication_tables.py | 300 | 4.125 | 4 | def multiplication_table(number):
for i in range (10):
print(str(number) + ' x ' + str(i) + ' = ' + str(number*i))
def run():
number = int(input('Enter the number you want to know the multiplication table: '))
multiplication_table(number)
if __name__ == '__main__':
run() | false |
8cb06562dd43a5863811bf471e0ecf94baa7d1f1 | juandaangarita/CursoBasicoPython | /Fibonacci.py | 795 | 4.59375 | 5 | def fibonacci(nth):
fibonacci_sequence = [0, 1]
for i in range(2, nth + 1):
fibonacci_sequence.append(fibonacci_sequence[i-1] + fibonacci_sequence[i-2])
print(fibonacci_sequence)
def fibonacci_recursion(nth):
"""
Calculate fibonacci sequence of a number in a recursive way
:param nth: Number nth you want to calculate fibonnaci sequence
type: int
returns: Fibonnaci sequence of nth
"""
if nth == 0 or nth == 1:
return 1
return fibonacci_recursion(nth - 1) + fibonacci_recursion(nth - 2)
def run():
print('This is a program to calculate a Fibonacci sequence')
nth = int(input('Enter the number nth number you want to calculate: '))
fibonacci(nth)
print(fibonacci_recursion(nth))
if __name__=='__main__':
run() | false |
9a0fc1b30c2cbdc5926cf542bfab58d841f7f90d | juliaguida/learning_python | /week8/leap_year.py | 891 | 4.46875 | 4 | # def year_leap(year):
# #If a year is multiple of 400 it is a leap year.
# if year %400 == 0:
# #print('This is a year leap ')
# if year %4 == 0:
# #print('This is a year leap')
# if year %100 == 0:
# #print('This is not a year leap')
# return True
# else:
# return False
# else:
# return True
# year = 2020
# def year_leap(year)
year_leap = int(input('Please enter a year: '))
#If a year is multiple of 400 it is a leap year.
if year_leap %400 == 0:
print('Leap year{}'.format(year_leap))
#If a year is multiple of 4 then it is a leap year
if year_leap %4 == 0:
print('This is a leap {}'.format(year_leap))
#If a year is multiple of 100 then it is not a leap year
if year_leap %100 != 0:
print( 'This is not a leap year {}'.format(year_leap))
#else:
#print(" I don't know ") | false |
705ab198790777f50fbf874d7beff92f974c7c43 | juliaguida/learning_python | /week5/function_add.py | 289 | 4.125 | 4 | # Write a program that takes 2 numbers as arguments to a function and returns the sum of those 2 numbers
def add_func(number1,number2):
return number1 + number2
numb1 = int(input('Enter a number: '))
numb2 = int(input('Enter another: '))
result = add_func(numb1,numb2)
print(result) | true |
b9691374f143af16f1cdc6065a7d727f09b16964 | juliaguida/learning_python | /week4/choose_a_side.py | 385 | 4.28125 | 4 | import turtle
def shape(number_of_sides,side_length):
angle = 360/number_of_sides
for i in range(number_of_sides):
turtle.forward(side_length)
turtle.right(angle)
turtle.done()
number_of_sides = int(input('Please input the numbers of side: '))
side_length = int(input('Please input the of side length: '))
shape(number_of_sides,side_length)
| true |
eec05c50c073b60c0bf7d04b046c3501e33580ff | juliaguida/learning_python | /homework.py/week8/check_numb.py | 235 | 4.6875 | 5 | # This code checks if a number is positive or negative
number = float(input('Please enter a number to check if it is negative or positive.'))
if number > 0:
print('The input is positive')
else:
print( 'This input is negative')
| true |
4c79e7f0179e3220a55ec56c15845cb283abf844 | wafarifki/Hacktoberfest2021 | /Python/linked_list_reverse.py | 853 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None # Head of list
def reverse(self, head):
if head is None or head.next is None:
return head
rest = self.reverse(head.next)
head.next.next = head
head.next = None
return rest
def __str__(self):
linkedListStr = ""
temp = self.head
while temp:
linkedListStr = (linkedListStr +
str(temp.data) + " ")
temp = temp.next
return linkedListStr
def push(self, data):
temp = Node(data)
temp.next = self.head
self.head = temp
linkedList = LinkedList()
linkedList.push(20)
linkedList.push(4)
linkedList.push(15)
linkedList.push(85)
print("Given linked list")
print(linkedList)
linkedList.head = linkedList.reverse(linkedList.head)
print("Reversed linked list")
print(linkedList)
| true |
f5e60e6364aa94698b52f6bf9faf42cda94f19e7 | franktank/py-practice | /fb/hard/145-binary-tree-postorder-traversal.py | 1,324 | 4.125 | 4 | """
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
self.postorder_path = []
self.postorder_iterative(root)
self.postorder_path.reverse()
return self.postorder_path
def postorder(self, root):
if root == None:
return
self.postorder(root.left)
self.postorder(root.right)
self.postorder_path.append(root.val)
def postorder_iterative(self, root):
stack = list()
stack.append(root)
while stack:
curr_node = stack.pop()
self.postorder_path.append(curr_node.val)
# reverse of preorder
if curr_node.left:
stack.append(curr_node.left)
if curr_node.right:
stack.append(curr_node.right)
| true |
6fb49004c5a722c118e6ac007c4b58945f169f01 | Selva0810/python-learn | /string_to_integer.py | 2,814 | 4.25 | 4 |
'''
String to Integer (atoi)
Solution
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.
Example 1:
Input: str = "42"
Output: 42
Example 2:
Input: str = " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.
'''
from typing import List
class Solution:
def myAtoi(self, s: str) -> int:
chars = (c for c in s)
ss = []
while True:
try:
current = next(chars)
space = current.isspace()
pm = current in '+-'
if space and ss:
break
if pm and ss:
break
if not current.isnumeric() and not space and not pm:
break
if not space:
ss.append(current)
except StopIteration:
break
try:
number = int(''.join(ss).strip())
if number < 0:
return max(-2**31,number)
return min(2**31-1,number)
except ValueError:
return 0
soln = Solution()
s = " -42 "
print(soln.myAtoi(s))
| true |
5b399f2b01afcc2f26ad07af5108e38e22eb2315 | hoppang0817/Python | /If-else.py | 1,146 | 4.125 | 4 | if True:
print('if문 실행1')
print('if문 실행2')
print('if문 실행3')
print('if문아님')
name = 'Alice'
if name == 'Alice':
print('Hi,Alice')
print('종료')
print('\n')
# if else
# name = '밥'
# if name == '앨리스':
# print('당신이 앨리스군요')
# else:
# print('누구인가')
# if elif else
name = '밥'
if name == '앨리스':
print('당신이 앨리스군요')
elif name == '밥':
print('당신이 밥이군요')
elif name == '펭수':
print('당신이 펭수이군요')
else:
print('누구인가')
number = int(input('숫자를 입력 : \n'))
if number % 2 == 0:
print("짝수 입니다")
else:
print("홀수 입니다")
height = int(input('키를 cm로 입력해 주세요 : \n'))
if height > 120:
print('청룡열차를 탈수 있습니다')
age = int(input('나이를 입력해 주세요 : \n'))
if age < 12:
print('요금은 5000원 입니다')
elif age >= 12 and age <= 18:
print('요금은 7000원 입니다')
else:
print('요금은 12000원 입니다')
else:
print('죄송하지만 탈수 없습니다')
| false |
3e818dbefab6bd432a04a9fa1332ef0aaa44ad70 | asadiqbalkhan/shinanigan | /Games/guess.py | 1,404 | 4.34375 | 4 | # This is a guess the random number game
# import random function
# Author: Asad Iqbal
# Language: python 3
# Date: 18 - June - 2017
import random
# variable to store the total guesses done by the player
guesses_taken = 0
# Display welcome message to the player
# Input required by the player at this stage to proceed
print('Hello! , What is your name player?')
pName = input('> ')
# random.randint(x, y) function from import random
number = random.randint(1, 20)
# print message using string concatination
print('Well, ' + pName + ', I am thinking of a number between 1 and 20.')
# run while loop 6 times to give player 6 chances to guess the number
while guesses_taken < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
# Increment the guesses taken by player by 1 as each chance goes by
guesses_taken = guesses_taken + 1
# Developing game logic using if statements
if guess < number:
print('Your guess is too low try a higher number')
if guess > number:
print('Your guess is too high try a lower number')
if guess == number:
break
# If player wins display this message
if guess == number:
guesses_taken = str(guesses_taken)
print('Good Job, ' + pName +'! You guessed the number in '+ guesses_taken + ' guesses!')
# If player loses display this message
if guess != number:
number = str(number)
print("You've had 6 chances to guess the number.\n The number was " + number)
| true |
7d770f3d71e16201a74e82b07fe793ca00679139 | JunboChen94/Leetcode | /junbo/LC_173.py | 1,378 | 4.125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
'''
Based on inorder
'''
def __init__(self, root: TreeNode):
self.stack = []
self.root = root
def next(self) -> int:
"""
@return the next smallest number
"""
while self.root:
self.stack.append(self.root)
self.root = self.root.left
node = self.stack.pop()
self.root = node.right
return node.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self.root or self.stack
'''
Based on inorder, other slightly different version
'''
def __init__(self, root: TreeNode):
self.stack = []
self.pushAll(root)
def next(self) -> int:
"""
@return the next smallest number
"""
node = self.stack.pop()
self.pushAll(node.right)
return node.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self.stack
def pushAll(self, root: TreeNode):
while root:
self.stack.append(root)
root = root.left
| true |
672a9eeac7871138036f566ae12e4ca6b9137e15 | Collinslenjo/pythondata | /hello-world/datatypes.py | 1,960 | 4.15625 | 4 | # Datatypes and Ints using operators
#Addition
age1 = 20
age2 = 42
age3 = age1 + age2
print(age3)
#subtraction
age1 = 20
age2 = 42
age3 = age1 - age2
print(age3)
#multiplication
age1 = 20
age2 = 42
age3 = age1 * age2
print(age3)
#division
age1 = 20
age2 = 42
age3 = age1 / age2
print(age3)
#modulus
age1 = 20
age2 = 42
age3 = age1 % age2
print(age3)
# Datatypes in strings
# concatenating
firstname = "Collins"
lastname = "Lenjo"
fullname = firstname + " " + lastname
print(fullname)
# return one only (slice)
random = "collo kjrgfvyhurthgehgiojgekrhbij;gkdhufiugj erghlflije"
getter = random[0:5]
ally = random[0:]
print(ally)
print(getter)
# DataTypes Lists
shoppingList =["apples", "carrots", "milk", "bread", "eggs"]
print(shoppingList[2])
#deleting from a list
del shoppingList[2] #function
print (shoppingList)
array1 = [12,23,56]
array2 = [52,25,76]
array3 = array1 + array2
print(array3)
print len(shoppingList) #function
numArray = [150,4000, 380, 46]
print max(numArray) #function
print min(numArray) #function
shoppingList.append("Brocoli") #function
print (shoppingList)
print shoppingList.count("carrots") #function
# Dictionaries Datatypes
students = {"Erick":14,"Victor":12,"Tina":26,"Chris":15}
print students["Victor"]
#Updating the dicionary
students["Victor"] = 13;
print students["Victor"]
#deleting
del students["Victor"]
print(students)
'''
Dictionary functions
'''
students = {"Steve":12,"Prof":16,"Edgar":14}
students.clear() #clearing sunctions
print students
#del students
#print students
students = {"Steve":12,"Prof":16,"Edgar":14}
print len(students) #function
print students.keys() #function
print students.values() #function
student2 = {"Erick":14,"Victor":12,"Tina":26,"Chris":15}
students.update(student2)
print students
'''
Tupples Datatypes like const in other programming langs
They are defined by normal round brackets
(Only create them again but not rewritable)
'''
tup1 = ("Maths",23,"Dogs")
print tup1[0:3] | false |
b1fac02cb617d774d738774769c6a836fc15607c | smkrishnan22/python-basics-to-ml | /language/Product.py | 753 | 4.375 | 4 | '''
class Product:
# Default Constructor.
def __init__(self):
self.productid = 10
self.productname = "Ashok"
_instance = Product()
print(_instance.productid)
'''
class Product:
# This is Constructor.
# We can have only one constructor in Python.
def __init__(self, ids, name):
self.productid = ids
self.productname = name
_instance = Product(10, "Ashok")
print(_instance.productid)
print(_instance.productname)
# Here SeasonProduct is extending Product
class SeasonProduct(Product):
def __init__(self, ids, name):
self.productid = ids
self.productname = name
_instance = SeasonProduct(100, "Ram")
print(_instance.productid)
print(_instance.productname) | true |
d9f51fbaf3cf11226bf18110aa04a79c3be58883 | jyotsanaaa/Python_Programs | /find_lcm.py | 341 | 4.21875 | 4 | #Find LCM
#LCM Formula = (x*y)//gcd(x,y)
num1 = int(input("Enter lower num : "))
num2 = int(input("Enter greater num : "))
#To find GCD
def gcd(x,y):
while(y):
x,y = y, x%y
return x
#To find LCM
def lcm(a,b):
lcm = (a*b)//gcd(a,b)
return lcm
print(f"LCM of {num1} and {num2} is :",lcm(num1,num2)) | true |
3460833f74721665e81bd89924e6fcd2e33691df | jyotsanaaa/Python_Programs | /conversion.py | 237 | 4.34375 | 4 | #Convert decimal to binary, octal and hexadecimal
num = int(input("Enter number in decimal : "))
print(f"\nConversion of {num} Decimal to :- ")
print("Binary :",bin(num))
print("Octal :",oct(num))
print("Hexadecimal :",hex(num)) | true |
39a1712a4f8f9e2e3ed646a1e45fe209f34d3457 | jyotsanaaa/Python_Programs | /armstrong_num.py | 588 | 4.21875 | 4 | #Armstrong Number
"""An Armstrong number is an n-digit base b number such that the sum of its (base b) digits raised to the power n is the number itself.
Eg: 407 is sum of cube of three num i.e.4,0,7 && 1634 is sum of ^4 of 4 num i.e.1,6,3,4"""
#import math
n = int(input("Enter number : "))
order = len(str(n))
#order = int(math.log10(n))+1 #adding 1 gives number of digits
sum = 0
temp = n
while temp > 0:
digit = temp % 10
sum = sum + digit ** order
temp //= 10
if sum == n:
print(f"{n} is an armstrong number.")
else:
print(f"{n} is not an armstrong number.")
| true |
b659bb7fa3f753e538e21d80c5708e24a877df7d | Anvitha-N/My-Python-Codes | /assign list.py | 402 | 4.4375 | 4 | #Assigning elements to different lists:
animals = ["dog","monkey","elephant","giraffee"]
print(animals)
#replace
animals[1] = "chrocodile"
print(animals)
#insert
animals.insert(2,"squirrel")
print(animals)
#sort
animals.sort()
print(animals)
#delete
del animals[0]
print(animals)
#append
animals.append("panda")
print(animals)
#reverse
animals.reverse()
print(animals)
| true |
1aba9eba32f19c6c6cf27ad8bd7ad508a36623cc | aniqmakhani/PythonTraining | /Assignment3.py | 1,716 | 4.1875 | 4 | # Question No: 01 Write a Solution to reverse every alternate k characters from a
# string. Ex. k = 2 , Input_str ="abcdefg", Output_str = bacdfeg"
print("Question 1: ")
Input_str = input("Enter a string: ")
k = int(input("Enter a value for k: "))
inp = list(Input_str)
for i in range(0,len(inp),k+2):
if i+1 < len(inp):
inp[i], inp[i+1] = inp[i+1], inp[i]
inp = "".join(inp)
print(inp)
#-----------------------------------------------------------
# Question No: 02 Write a Solution to replace unwanted charecters("CON") from the
# String. Ex. Input_str = "PCONECONCONN", Output_str = "P E N"
print("\nQuestion 2: ")
Input_str = "PCONECONCONN"
print(Input_str)
print(Input_str.replace("CON", ''))
#-------------------------------------------------------------
# Question No: 03 Write a solution to replace the Character value with its
# corresponding value from the String. Replace 'A' with 'T', 'T' with 'A' and 'C' with 'G',
# ''G' with 'C'. Input_str ="ATTCGGTAG", Output_str = "TAAGCCATC"
print("\nQuestion 3: ")
str_dict = { 'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C' }
x = input("Enter a string: ")
new_str = []
for str in x:
new_str.append(str_dict.get(str, ''))
final_str = "".join(new_str)
print(final_str)
#----------------------------------------------------------------
# Question No: 04 Write a Solution to fetch out the serial number from the given
# Reciept Input of Product. The serial number will be fetched by combining all the
# values of date printed over the Receipt. Input_str = "2012-18-10 Speaker Harman",
# Output_str = "20121810"
import re
print("\nQuestion 4: ")
inp_str = "2012-18-10 Speaker Harman"
num = re.findall("\d+", inp_str)
num = "".join(num)
print(num)
| true |
9e9d2b081559d045b18042e00fa8f2cb93ec737d | venkat79/java-python | /python/src/main/python/testscripts-master/inner/couple.py | 1,016 | 4.5 | 4 | '''
Consider the following sequence of string manipulations -
abccba
abccba - "cc" is a couple as both appear together. Remove the couple from the string and count as "1 couple"
abba - Resulting string after removing the couple
abba - Now "bb" is a couple. Remove the couple from the string and increment the count to 2
aa - After removing the above couple
aa - Now "aa" is a couple. Remove the couple from the string and increment the count to 3
'''
import sys
def removeduplicate(string):
l = []
count = 0
top = -1
for ch in string:
if len(l) == 0:
l.append(ch)
top = 0
elif ch == l[top]:
l.pop()
top = top - 1
count = count + 1
else:
l.append(ch)
top = top + 1
return ''.join(l), count
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Error: Insufficient argument"
else:
res, count = removeduplicate(sys.argv[1])
print res, count
| true |
b4396c661758a357af1ce8df15fffe7cc527e0a4 | JiteshCR7/Python_Lab | /lab2.py | 2,537 | 4.125 | 4 | Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> 2**5
32
>>> a=20
>>> b=30
>>> c=a+b
>>> c
50
>>> a=input("enter value of a;")
enter value of a;20
>>> b=input("enter value of b;")
enter value of b;30
>>> c=a+b
>>> c
'2030'
>>> int(input("enter value of a;"))
enter value of a;20
20
>>> int(nput("enter value of b;"))
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
int(nput("enter value of b;"))
NameError: name 'nput' is not defined
>>> int(input("enter value of b;"))
enter value of b;30
30
>>> c=a+b
>>> int(c=a+b)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
int(c=a+b)
TypeError: 'c' is an invalid keyword argument for int()
>>> a="python programming"
>>> print(a.upper())
PYTHON PROGRAMMING
>>> print(a.lower())
python programming
>>> print(a.replace("python","c"))
c programming
>>> a=[1,2,3,4,8,-1,2.2,'b']
>>> a.append(5)
>>> a
[1, 2, 3, 4, 8, -1, 2.2, 'b', 5]
>>> b=[1,2,3]
>>> a.extend(['a','b'])
>>> a
[1, 2, 3, 4, 8, -1, 2.2, 'b', 5, 'a', 'b']
>>> a.extend(b)
>>> a=[1,2]
>>> b=[3,4]
>>> a.extend(b)
>>> a
[1, 2, 3, 4]
>>> a=[-1,4,5]
>>> b=[7,8,9]
>>> a+b
[-1, 4, 5, 7, 8, 9]
>>> a.index(-1)
0
>>> a=["CMR","good","college"]
>>> a.insert(1,"is")
>>> a
['CMR', 'is', 'good', 'college']
>>> a.replace("college","university")
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
a.replace("college","university")
AttributeError: 'list' object has no attribute 'replace'
>>> a.insert(3,"university")
>>> a
['CMR', 'is', 'good', 'university', 'college']
>>> a.remove(4)
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
a.remove(4)
ValueError: list.remove(x): x not in list
>>> a.remove(4,"college")
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
a.remove(4,"college")
TypeError: remove() takes exactly one argument (2 given)
>>> a.remove("college",/)
SyntaxError: invalid syntax
>>> a
['CMR', 'is', 'good', 'university', 'college']
>>> a.remove("college")
>>> a
['CMR', 'is', 'good', 'university']
>>> a=[1,2,4,8,-1,2.2,'b',2,2]
>>> a.count(2)
3
>>> a=[1,2,3]
>>> a[0;2]
SyntaxError: invalid syntax
>>> a[0:2]
[1, 2]
>>> a=(1,2,3,"a")
>>> a.append(5)
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
a.append(5)
AttributeError: 'tuple' object has no attribute 'append'
>>> a
(1, 2, 3, 'a')
>>> a*2
(1, 2, 3, 'a', 1, 2, 3, 'a')
>>>
| true |
5c0984cc0b0a40f72149458f3ac64e11e1f7080b | LEXW3B/PYTHON | /python/exercicios mundo 1/ex005/ex007.py | 516 | 4.25 | 4 | #faça um programa que leia uma frase pelo teclado e mostre.(quantas vezes aparece a letra 'a'),(em que posição aparece a primeira vez),(em que posição ela aparece a ultima vez).
frase = str(input('digite uma frase: ')).upper().strip()
print('a letra A aparece {} vezes na frase'.format(frase.count('A')))
print('a primeira letra A apareceu na posição {}'.format(frase.find('A')+1))
print('a letra A apareceu pela ultima vez na posição {}'.format(frase.rfind('A')+1))
#FIM//A\\
| false |
a89692d005e1004b5aa9ea7ebe98f5678f2e7ea2 | LEXW3B/PYTHON | /python/exercicios mundo 2/ex56_65.py/ex009.py | 823 | 4.28125 | 4 | '''65-CRIE UM PROGRAMA QUE LEIA VARIOS NUMEROS INTEIROS PELO TECLADO. NO FINAL DA EXECUÇÃO , MOSTRE A MEDIA ENTRE TODOS OS VALORES E QUAL FOI O MAIOR E O MENOR VALOR LIDO. O PROGRAMA DEVE PERGUNTAR AO USUARIO SE ELE QUER OU NÃO CONTINUAR A DIGITAR VALORES. '''
resposta='S'
soma=quantidade=media=maior=menor=0
while resposta in 'Ss':
n=int(input('digite numero: '))
soma+=n
quantidade+=1
if quantidade ==1:
maior=menor=n
else:
if n>maior:
maior=n
if n<menor:
menor=n
resposta=str(input('quer continuar? [S/N] ')).upper().strip()[0]
media=soma/quantidade
print('voce digitou {} numeros e a media foi {}'.format(quantidade, media))
print('o maior numero foi {} e o menor numero foi {}'.format(maior, menor))
#FIM//A\\ | false |
857a992f5c12f1730f642e0f3682746df4dabb19 | abhiramvenugopal/vscode | /Spoj_test/String_Rotation.py | 493 | 4.15625 | 4 | def isSubstring(s1, s2):
if s1.find(s2) != -1:
return True
if s2.find(s1) != -1:
return True
return False
## Do not change anything above
def isRotation(s1,s2):
s1s1=s1+s1
print(isSubstring(s2,s1s1))
## You can only call isSubstring function from this function once. Use this function to check if s2 is a rotation of s1.
## Do not change anything below
t = int(input())
for i in range(t):
s1 = input()
s2 = input()
isRotation(s1,s2) | true |
b434bbb41e4676059a29526d553ffab35cb337aa | abhiramvenugopal/vscode | /5-26-2021/even_odd_seperator.py | 616 | 4.28125 | 4 | # Write a function with name even_odd_separator, you should exactly the same name
# This even_odd_separator functions should take a list of integers and return a list
# you can start from here
def even_odd_separator(numbers):
odd_list=[]
even_list=[]
for i in numbers:
if i%2==0:
even_list.append(i)
else:
odd_list.append(i)
return odd_list+even_list
### Do not change anything below this line
if __name__ == "__main__":
numbers = [int(i) for i in input().split(' ')]
separated = even_odd_separator(numbers)
for num in separated:
print(num) | true |
4435d655b68aa16413b065fcfcb71e78fdebd920 | abhiramvenugopal/vscode | /5-16-2021/int_palindrome.py | 384 | 4.125 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward
# Input
# 1 containing integer
# Output
# 1 line containing Boolean value
# Example
# Input: 121
# Output: True
# Input: 10
# Output: False
# -----------------------------------------------------------------------
n=int(input())
print(n==int(str(n)[::-1])) | true |
771febd6086b7ad67fa38173fb1be2b77c08fb47 | abhiramvenugopal/vscode | /special/odd_even_or_one_zero_subset.py | 1,094 | 4.28125 | 4 | # You are given an array A of N positive integer values. A subarray of this array is called Odd-Even subarray if the number of odd integers in this subarray is equal to the number of even integers in this subarray.
# Find the number of Odd-Even subarrays for the given array.
# Input
# The input consists of two lines.
# First line denotes N - size of array.
# Second line contains N space separated positive integers denoting the elements of array A.
# Output
# Print a single integer, denoting the number of Odd-Even subarrays for the given array.
# Example
# Input:
# 4
# 1 2 1 2
# Output:
# 4
# also we can do this prokgrame can use for zero one case also
def countOddEvenSubArray(arr,n):
dict={}
count=0
sum=0
for i in range(n):
if arr[i]%2==0:
arr[i]=-1
else:
arr[i]=1
sum+=arr[i]
if sum==0:
count+=1
if sum in dict:
count+=dict[sum]
dict[sum]=dict.get(sum,0)+1
print(count)
n=int(input())
arr=[int(i) for i in input().split()]
countOddEvenSubArray(arr,n)
| true |
7dc39930c14219cb9f4badd0dce651d25368af14 | vmsouza30/520 | /Aula2/media3.py | 841 | 4.125 | 4 | #!/usr/bin/python3
# está validando para entrada de nova até 10, se for maior avisa com erro, e faz a qtdade -1 para tirar da media
# caso queira que force sempre para entrar com um valor correto, utilizar WHILE e tirar qtdade -1
qtdadenotas = int(input('Digite a quantidade de notas: '))
total = 0
# ou total = float(0)
for x in range(qtdadenotas):
nota = int(input('Digite a nota{}: '.format(x+1)))
if nota > 10:
print ('Nota invalida!')
qtdadenotas -= 1 # é necessario colocar essa variavel para nao contabilizar na media um valor invalido
continue
total += nota
media = total/ qtdadenotas
# media = (faz o calculo direto)
if media >= 7 :
print (media,'Aprovado')
elif media <=3 :
print(media,'Reprovado')
else:
print(media,'Media')
# sempre endentado para funcionar | false |
a30f89daa5285607b61fe43398259de765d1ba61 | nfredrik/pyjunk | /regexps/notmatch.py | 442 | 4.3125 | 4 | import re
#
#I'm looking for a regular expression that will match all strings EXCEPT those that contain
# a certain string within. Can someone help me construct it?
#For example, looking for all strings that do not have a, b, and c in them in that order.
#So
#abasfaf3 would match, whereas
#asasdfbasc would not
r = re.compile("(?!^.*a.*b.*c.*$)")
r.match("abc")
r.match("xxabcxx")
r.match("ab ")
r.match("abasfaf3")
r.match("asasdfbasc")
| true |
81a86c2aa78e6ed3f85d3d8a842548b99c0fe19a | CodaGott/introtopythonforcomputerscienceanddatascienceexercises | /Chapter_two_exercises/Exercise2.2.py | 495 | 4.15625 | 4 | """ (What’s wrong with this code?) The following code should read an integer into the
variable rating:
rating = input('Enter an integer rating between 1 and 10') """
rating = input('Enter an integer rating between 1 and 10')
""" The above code can be casted on declaration
or casted at calculation
to cast as the beginning of the code we can place the code
input module into the int() module.
or we can cast the variable by placing it into the int()
module.""" | true |
2c64537f7f567b2dc9dda6f18049aad51798a4cc | CodaGott/introtopythonforcomputerscienceanddatascienceexercises | /Chapter_two_exercises/ChapterOneExercises.py | 460 | 4.53125 | 5 | """ (What does this code do?) Create the variables x = 2 and y = 3, then determine what
each of the following statements displays:
a) print('x =', x)
b) print('Value of', x, '+', x, 'is', (x + x))
c) print('x =')
d) print((x + y), '=', (y + x)) """
x = 2
y = 3
print('x=', x) #this will print 2
print('Value of', x, '+', x, 'is', (x + x)) #this will print 4
print('x =') #this will print 'x ='
print((x + y), '=', (y + x)) #this will print 5 for each sides
| true |
20549ee8b2bd75ddb1542eac4b074b2e94bafdc4 | gordonmannen/The-Tech-Academy-Course-Work | /Python/Python 3 Essential Training - Py3.5.1/GettingStarted.py | 2,247 | 4.125 | 4 | print("Hello, World!")
a, b = 0, 1
if a < b:
print('a ({}) is less than b ({})'.format(a, b))
else:
print('a ({}) is not less than b ({})'.format(a, b))
a, b = 5, 1
if a < b:
print('a ({}) is less than b ({})'.format(a, b))
else:
print('a ({}) is not less than b ({})'.format(a, b))
# blocks are called suites in the Python documentation.
# 4 spaces is the traditional Python indentation, but one space would also work.
print("foo" if a < b else "bar")
a, b = 0, 1
print("foo" if a < b else "bar")
# simple fibonacci series
# the sum of two elements defines the next set
a, b = 0, 1
while b < 50:
print(b)
a, b = b, a + b
# read the lines from the file
# for loops work with iterators
fh = open('lines.txt')
for line in fh.readlines():
print(line, end='')
def isprime(n):
if n == 1:
print("1 is special")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
else:
print(n, "is a prime number")
return True
# the variable used here can be called n, but it isn't actually the same n as that
# referenced above, so it might make it clearer to use a different letter.
for x in range(1, 20):
isprime(x)
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n = 1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
# simple fibonacci series
# the sum of two elements defines the next set
# class - the definition or blueprint used to create an object. Objects are instances of classes.
# self is a traditional choice for the first instance, it doesn't have to be used, but is common.
# the init function is a constructor.
class Fibonacci():
def __init__(self, a, b):
self.a = a
self.b = b
def series(self):
while(True):
yield(self.b)
self.a, self.b = self.b, self.a + self.b
# instantiating, creating an instance of the class (that instance is an object).
f = Fibonacci(0, 1)
for r in f.series():
if r > 100: break
print(r, end=' ')
| true |
cb34d3c7a7399b0f513fb090182eef540f89adb8 | Menelisi-collab/Classes-exercise | /izibalo.py | 532 | 4.125 | 4 | def task(self):
a = int(input("Enter a Number: "))
b = int(input("Enter another Number: "))
total = (a + b) or (a - b) or (a * b) or (a / b)
if total == (a + b):
print(f"The added result is: {total}")
elif total == (a - b):
print(f"The subtracted result is: {total}")
elif total == (a * b):
print(f"The multiplied result is: {total}")
elif total == (a / b):
print(f"The divided result is: {total}")
else:
print("You have not entered any numbers to process")
| true |
9ed540608eca140a8697e457b03b38d4095fe363 | lakshay451/Deep-Neural-Networks-with-PyTorch | /Week 1/2_D Tensors.py | 2,461 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
2-D Tensors
"""
"""
A 2d tensor can be viewed as a container the holds numerical values of the same type.
In 2D tensors are essentially a matrix. Each row is a different sample and each column is a feature or attribute.
We can also represent gray-scale images as 2D tensors.
The image intensity values can be represented as numbers between 0 and 255. 0 corresponds to color black and 255 white.
Tensors can be extended to any number of dimensions. A 3D tensor is a combination of 3 1D tensors.
"""
import torch
import numpy
import pandas
#Lets create a 2-D tensor
#We first create a list with 3 nested lists.
a = [[11,12,13], [21,22,23], [31,32,33]]
b = torch.tensor([[11,12,13], [21,22,23], [31,32,33]])
#We then cast the list to a torch tensor
A = torch.tensor(a)
print(A)
#Lets check the no. of dimensions or rank
print("Numer of dimensions of A = ", A.ndimension())
#The first list [] represents the first dimensions and the second represents the second dimension
#2D Tensors is as follows: [[]]
#Lets check the number of rows and columns of A. It should be 3,3 --- 3 rows, 3 columns
print("Shape of tensor A: ", A.shape)
#OR
print("Shape of tensor A: ", A.size())
#The 3,3 tensor has 2 axes. Axis = 0 (vertical) and Axis = 1 (Horizontal)
#Number of elements in a tensor -- using numel() method
print("Number of elements in A: ", A.numel())
#Indexing and Slicing 2D Tensors
#Indexing
print(A)
A[0][1] #Element in 1st row and 2nd column
A[1][2] #Element in 2nd row and 3rd column
A[2][0] #Element in 3rd row and first column
#Slicing
A[1:3,2] #Slicing elements in rows 2 and 3 from the 3rd column
A[2,0:3] #Slicing all the elements in the 3rd row
#Adding 2D tensors only works for tensors of the same type
#Lets add A and B. Elements of the same position will be added
B = torch.tensor([[11,12,13], [21,22,23], [31,32,33]])
C = A + B
C
#Multiplication by a scalar is the same as multiplying a matrix by a scalr
#Multiplication of tensors is an elemenet-wise multiplication. Same position elements
D = A*B
print(D)
#Matrix multiplication can be done in torch but same rules will apply
#First matrix must have equal columns to the rows of the second matrix
A = torch.tensor([[0,1,1],[1,0,1]])
B = torch.tensor([[1,1],[1,1],[-1,1]])
#Matrix multiplication is done by using the mm method
C = torch.mm(A,B)
print(C)
| true |
afef11b98745fda79c08dfeada6308919b6f4e54 | yerimJu/crawling_examples | /src/using_DB/sqlite3_test.py | 604 | 4.46875 | 4 | import sqlite3 # standard library for Python
DB_PATH = 'test.sqlite'
conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()
cur.executescript('''
DROP TABLE IF EXISTS items;
CREATE TABLE items(
item_id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
price INTEGER
);
INSERT INTO items(name, price) VALUES ('Apple', 800);
INSERT INTO items(name, price) VALUES ('Orange', 700);
INSERT INTO items(name, price) VALUES ('Banana', 600);
''')
# apply db
conn.commit()
cur = conn.cursor()
cur.execute("SELECT item_id, name, price FROM items")
item_list = cur.fetchall()
for it in item_list:
print(it)
| true |
7bc6de20ac5d4841019ad7c2917ea9750367f668 | garciagenrique/template_project_escape | /template_project_escape/code_template_escape.py | 1,213 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Template module with an example for the ESCAPE project
import numpy as np
import argparse
def square_number(number):
"""
Function that returns the square of the input number.
Parameters:
-----------
number: int or float
Number to square.
Returns:
--------
np.square(number) : numpy.int64
The square of the input number. The result is rounded to 3 decimal places !
"""
return np.round(np.square(number), 3)
def main():
"""
Prints the output of the square_number function, passed as an argument.
"""
parser = argparse.ArgumentParser(description="Square the input number !")
parser.add_argument('--input_number', '-i',
type=float,
dest='input',
help='Input number to square. Default = -7.',
default=-7.
)
args = parser.parse_args()
print('\n\tThe square of {} is {} !\n'.format(args.input,
square_number(args.input)
))
if __name__ == '__main__':
main()
| true |
b8a91f071c64be352a59299c737e21c6d8161ba5 | chuajunyu/scvu-git-tutorial | /HW1/HW01_YuHong.py | 2,553 | 4.1875 | 4 | from operator import add, sub
#Question 1
def a_plus_abs_b(a, b):
# """Return a+abs(b), but without calling abs.
# >>> a_plus_abs_b(2, 3)
# 5
# >>> a_plus_abs_b(2, -3)
# 5
# """
if b < 0:
f = sub
else:
f = add
return f(a, b)
# print(a_plus_abs_b(5,10))
# print(a_plus_abs_b(5,-10))
#Question 2
def two_of_three(a, b, c):
# """Return x*x + y*y, where x and y are the two largest members of the
# positive numbers a, b, and c.
# >>> two_of_three(1, 2, 3)
# 13
# >>> two_of_three(5, 3, 1)
# 34
# >>> two_of_three(10, 2, 8)
# 164
# >>> two_of_three(5, 5, 5)
# 50
# """
noList = [a,b,c]
big1 = max(noList)
noList.remove(max(noList))
big2 = max(noList)
return big1*big1 , big2*big2
#print(two_of_three(1,2,3))
#Question 3
def largest_factor(n):
# """Return the largest factor of n that is smaller than n.
# >>> largest_factor(15) # factors are 1, 3, 5
# 5
# >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
# 40
# >>> largest_factor(13) # factor is 1 since 13 is prime
# 1
# """
factor = []
for i in range(1,n+1):
if n%i==0:
factor.append(i)
if len(factor) == 2:
print(f"Factor is 1 since {n} is a prime number")
else:
facs = ""
for fac in factor:
facs += " "+str(fac)
print(f"Factors are{facs}")
#largest_factor(14)
#Question 4
def if_function(condition, true_result, false_result):
if condition:
return true_result
else:
return false_result
def with_if_statement():
if c():
return t()
else:
return f()
def with_if_function():
return if_function(c(), t(), f())
#Condition
def c():
return False
def t():
print(1)
return 1
def f():
return 2
# print(with_if_function())
# print(with_if_statement())
#Question 5
def hailstone(n):
"""Print the hailstone sequence starting at n and return its
length.
>>> a = hailstone(10)
10
5
16
8
4
2
1
>>> a
7
"""
# Pick a positive integer n as the start.
# If n is even, divide it by 2.
# If n is odd, multiply it by 3 and add 1.
# Continue this process until n is 1.
"*** YOUR CODE HERE ***"
print(n)
i = 0
while n != 1:
if (n % 2) == 0:
n = int(n/2)
print(n)
else:
n = (n*3)+1
print(n)
i+=1
print(f"Number of loops: {i}")
#hailstone(26)
| false |
0db16e37cd7b9e2d3842aba851cadf5b3902db99 | ColeMaddison/hillel_python | /python_3/hw_3_1.py | 590 | 4.25 | 4 | # Задача-1
#
# Дан произвольный текст. Соберите все заглавные буквы в одно слово в том порядке
# как они встречаются в тексте.
# Например: текст = "How are you? Eh, ok. Low or Lower? Ohhh.", если мы соберем все
# заглавные буквы, то получим сообщение "HELLO".
text = "How are you? Eh, ok. Low or Lower? Ohhh."
def upper_case_word(text):
return ''.join([i for i in text if i.isupper()])
print(upper_case_word(text)) | false |
469bf83faa1aab82227c840113430b0b92437367 | rebeccaAhirsch/frc-hw-submissions | /lesson5/hw_5.py | 262 | 4.21875 | 4 | words = ["red", "blue", "green", "purple", "magenta", "great", "wonderful", "yay!", "koala", "hi"]
anything = raw_input("what's your favorite word?")
if (anything in words) == True:
print "i like that word too"
else:
words.append(anything)
print words
| true |
56f8ba5742d98072231765d565a7a7d479c875b1 | Ivanlxw/Exercises | /Mega Project LIst/Numbers/MortgageCalculator.py | 2,426 | 4.34375 | 4 | def calculate_payment():
"""
Calculate the monthly payments of a fixed term mortgage over Nth terms at a given interest rate.
Extra: add an option for users to select the compounding interval (Monthly, Weekly, Daily, Continually).
"""
interval = int(input("Select compounding interval:\n1.Monthly\n2.Weekly\n3.Daily\n"))
#take in inputs
r = float(input("Enter interest rate in decimals (yearly)\n"))
mortgage = float(input("How much is the mortgage?\n"))
period = float(input("How many years?\n"))
#adjust for time period
if interval == 1:
r /= 12
period *= 12
elif interval == 2:
r/=52
period *= 52
elif interval == 3:
r /= 365
period *= 365
#working
payment = mortgage * r / (1 - (1/(1+r))**period)
if interval == 1:
print("You'll need to pay $%.2f per month"% payment)
elif interval == 2:
print("You'll need to pay $%.2f per week" % payment)
elif interval == 3:
print("You'll need to pay $%.2f everyday" % payment)
def time_to_repay():
"""
Also figure out how long it will take the user to pay back the loan.
"""
interval = int(input("Select compounding interval:\n1.Monthly\n2.Weekly\n3.Daily\n"))
#take in inputs
r = float(input("Enter interest rate in decimals (yearly)\n"))
mortgage = float(input("How much is the mortgage?\n"))
payment = float(input("How much are you paying per time period?\n"))
if interval == 1:
r /= 12
elif interval == 2:
r/=52
elif interval == 3:
r /= 365
#working
temp = mortgage
period = -1
while temp > 0:
temp = (temp - payment) * (1+r)
period += 1
if interval == 1:
print("You'll need to take {} months".format(period))
elif interval == 2:
print("You'll need to take {} weeks".format(period))
elif interval == 3:
print("You'll need to take {} days".format(period))
if __name__ == '__main__':
while True:
option = int(input("Choose either option 1 or 2:\n1.Calculate monthly payment of mortgage\n2.Time needed to repay loan\n"))
if option == 1:
calculate_payment()
break
elif option == 2:
time_to_repay()
break
else:
print("Please enter the correct number option")
| true |
89e882d4aae56b3c457f1398e4e775d1f5fc6220 | yudianzhiyu/Notebook | /mystuff/ex30.py | 446 | 4.15625 | 4 | #!/usr/bin/python
people = 30
cars = 40
buses = 15
if cars > people:
print "we should take the cars."
elif cars < people:
print " we shoule not take the cars."
else:
print " we can't decide."
if buses> cars:
print "that's too many buses."
elif buses<cars:
print "may be we could take buses."
else:
print "we still can't decice."
if people > buses:
print "alright,let's just take the buses."
else:
print "file ,let's stay home then."
| true |
71ae734bbe1057377b22c9b5bf06ecfa649eee5d | silvesterriley/hello--world | /code.py | 736 | 4.1875 | 4 | message="hello python"
print(message)
#variables to hold my names
firstname="Silvester"
middlename="Muthiri"
lastname="Marubu"
Age=24
#i want to print my details
print("My first name is", firstname)
print("My middle name is" ,middlename)
print("My last name is" ,lastname)
print(Age,"years old")
#printing all variables in one line
print("My first name is {0} and My middle name is {1} and last name is {2} {3} years of age".format(firstname,middlename,lastname,Age))
#printing all variables in one line using percentage
print("My first name is %s and My middle name is %s and last name is %s %d years of age" %(firstname,middlename,lastname,Age))
#simple calculation
a=6
b=10
total = a+b
print(total) | true |
1081929f35684cb77485cbd588643048a6c142ae | sofide/ds_dices | /ds_dices.py | 1,463 | 4.28125 | 4 | black_dice = [0, 1, 1, 1, 2, 2]
blue_dice = [1, 1, 2, 2, 2, 3]
orange_dice = [1, 2, 2, 3, 3, 4]
def convert_string_to_dict_dices(string_input):
dices_str_list = string_input.split()
if not dices_str_list:
raise ValueError()
try:
dices_int_list = [int(n) for n in dices_str_list]
except ValueError as err:
raise err
if len(dices_int_list) < 3:
for n in range(3-len(dices_int_list)):
dices_int_list.append(0)
dices_dict = {
'black': dices_int_list[0],
'blue': dices_int_list[1],
'orange': dices_int_list[2]}
return dices_dict
def input_dices():
print('Insert your dices set with the next format:')
print('First number: black dices')
print('Second number: blue dices')
print('Third number: orange dices')
print('Each number has to be separeted by an espace')
print('You can ommit second and/or third number')
while True:
input_dices = input('Your dices set: ')
try:
print('trying')
dices_dict = convert_string_to_dict_dices(input_dices)
# desde acaaa print
break
except ValueError:
print('INVALID INPUT')
print('Please enter a correct input')
print('For example "1 2" for one black and two blue dices')
print('Excelent! Your set dice is:')
for k, v in dices_dict.items():
print(k, ': ', v)
input_dices()
| true |
730c640969690b391503c4446314d4a5148f787a | mxu007/daily_coding_problem_practice | /DCP_10_1.py | 2,195 | 4.15625 | 4 | # Determine if a cycle exists
# Given an UNDIRECTED graph, determine if it contains a cycle
# implement the solution using depth-first search. For each vertex in the graph, if it has not already been visited. we call our search function on it. This function will recursively traverse unvisited neighbors of the vertex and return True if we come accross the cycle.
# https://www.geeksforgeeks.org/detect-cycle-undirected-graph/
from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
# undirected graph
self.graph[u].append(v)
self.graph[v].append(u)
# O(V+E) time complexity where V is no.of verticies and E is no.of edges
# O(V) for visiting each vertice, E for adding each edge connected to the vertice currently visiting
# O(V) space for the call stack of traversing all possible verticies
def search(graph, vertex, visited, parent):
visited[vertex] = True
# graph is an adjacency list
# for neighbor iterate all possible edges
for neighbor in graph[vertex]:
# recursive call, but this is searching on the same level
if not visited[neighbor]:
# recursive call explore each possible verticies
if search(graph, neighbor, visited, vertex):
return True
# if this neighbor has been visited and this neighbor is not he parent of current vertex
# it indicates a cycle
elif parent != neighbor:
return True
return False
def has_cycle(graph):
visited = {v: False for v in graph.keys()}
for vertex in graph.keys():
if not visited[vertex]:
if search(graph, vertex, visited, None):
return True
return False
if __name__ == "__main__":
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
#g.addEdge(1, 2)
# g.addEdge(2, 0)
g.addEdge(2, 3)
#g.addEdge(3, 1)
print(has_cycle(g.graph))
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
#g.addEdge(1, 2)
g.addEdge(2, 3)
g.addEdge(3, 1)
print(has_cycle(g.graph))
| true |
ec4f6c3dc4159ec63b7535f4bd9cd8696d811a6b | mxu007/daily_coding_problem_practice | /DCP_7_2.py | 864 | 4.1875 | 4 | # Given a sorted array, convert it into a height-balanced binary search tree
# As asked for a height-balanced tree, we have to pick the middle value in the sorted array to be the root
class Node:
def __init__(self, data, left=None, right =None):
self.data = data
self.left = left
self.right = right
# O(N) time and space where N is no.of elements in the list
# As we have to make node for each element in the list
def make_BST(lst):
if not lst:
return None
# python 3 integer division
mid = len(lst) // 2
root = Node(lst[mid])
# recursive call
root.left = make_BST(lst[0:mid])
root.right = make_BST(lst[mid+1:])
return root
if __name__ == "__main__":
lst = [3,5,6,7,8,9,10]
root = make_BST(lst)
print(root.data, root.left.data, root.right.data, root.right.left.data) | true |
eaac00d6251b9da52cc54f0b2bde44f63b36a5db | mxu007/daily_coding_problem_practice | /DCP_1_2.py | 2,088 | 4.15625 | 4 | # Given an array of integers that are out of order, dtermine the bounds of the smallest window that must be sorted in order for the entire array to be sorted.
# Example Input: [3,7,5,6,9], Sorted Input: [3,5,6,7,9]
# Output: (1,3)
# Example Input: [1,5,2,3,8,6,7,9]
# Output: (1, 6)
# use python built-in sort function, then just loop through to trace left,right index where values are different to the sorted list
# O(NlogN) time complexity -- from the python sorted function
# O(NlogN) space complexity -- from the copied and sorted array/list
def smallest_window_to_sort_1(nums):
# use sorted for copy of sorted nums
sorted_nums = sorted(nums)
left, right = None, None
for i in range(len(nums)):
if nums[i] != sorted_nums[i]:
if left is None:
left = i
right = i
return left,right
# loop from left to right, compare running max with current value, if current value smaller than running max, update right flag
# loop from right to left, compare running min with current value, if currentv value is greater than running small, update left flag
# 2-pass O(N) time, O(1) space
def smallest_window_to_sort_2(nums):
left, right = None, None
running_max, running_min = nums[0], nums[-1]
for i in range(1,len(nums)):
if nums[i] < running_max:
right = i
running_max = nums[i] if nums[i] > running_max else running_max
for j in range(len(nums)-1,-1,-1):
if nums[j] > running_min:
left = j
running_min = nums[j] if nums[j] < running_min else running_min
return left,right
# solution from the book
def smallest_window_to_sort_3(array):
left, right = None, None
n = len(array)
max_seen, min_seen = -float("inf"), float("inf")
for i in range(n):
max_seen = max(max_seen, array[i])
if array[i] < max_seen:
right = i
for i in range(n-1, -1, -1):
min_seen = min(min_seen,array[i])
if array[i] > min_seen:
left = i
return left,right
| true |
89267563c2bcfd9d0f5c97344074423be79cd57b | kunjabijukchhe/python | /kunja14.py | 1,087 | 4.28125 | 4 | '''a= float(input("enter a first number:"))
b= float(input("enter a second number:"))
op=input("enter a operator:")
if op=="+":
print(a+b)
elif op =="-":
print(a - b)
elif op =="*":
print(a * b)
elif op =="/":
print(a / b)
else:
print("invalid")'''
def deposite(x,y):
return int(x)+int(y)
def withdraw(x,y):
return int(x)-int(y)
def kunja():
return kunja()
kunja()
amount=50000
name="kunja bijukchhe"
print("Enter your choice:\n1.Withdraw\n2.Deposite\n3.Show Balance")
choice=input("your choice is:")
if choice=='1':
a=input("Enter a withdraw amount:")
if int(a) <= int(amount):
print(withdraw(amount,a))
else:
print("invalid")
elif choice=='2':
b=input("Enter your deposit amount:")
print(deposite(amount,b))
elif choice=='3':
print("Your name is "+name+".")
print("your current balance is Rs."+str(amount))
else:
print("invaild")
c=input("Do you want to continues y/n")
if c=="y":
print(kunja())
else:
print("good bye")
| false |
a268bd67d22631549b68cf6d40c59bda9b5b62ec | PBNSan/Python-Code-Samples | /building_sets.py | 472 | 4.125 | 4 |
squares = set()
# todo: populate "squares" with the set of all of the integers less
# than 2000 that are square numbers
# Note: If you want to call the nearest_square function, you must define
# the function on a line before you call it. Feel free to move this code up!
def nearest_square(limit):
answer = 0
while (answer+1)**2 < limit:
answer += 1
squares.add((answer+1)**2)
return print(squares)
nearest_square(40)
| true |
fdc53ef4c37d355099124759f0c888fb077baeb6 | Bes0n/python2-codecademy | /projects/area_calculator.py | 920 | 4.375 | 4 | """
Area Calculator
Python is especially useful for doing math and can be used to automate many calculations. In this project, we'll create a calculator that can compute the area of the following shapes:
Circle
Triangle
The program should do the following:
Prompt the user to select a shape.
Calculate the area of that shape.
Print the area of that shape to the user.
Let's begin!
"""
print "Area Calculator program is running."
option = raw_input("Enter C for Circle or T for Triangle: ")
if option == 'C' :
radius = float(raw_input("Enter radius: "))
pi = 3.14159
area = pi * radius ** 2
print "Circle area: %d.2" % (area)
elif option == 'T' :
base = float(raw_input("Enter base: "))
height = float(raw_input("Enter height: "))
area = 0.5 * base * height
print "Triangle area: %d.2" % (area)
else:
print "Invalid shape entered"
print "Exiting Area Calculator program "
| true |
32cdc29f0c982373cb97107bafb3d9f0d1a16923 | althafuddin/python | /Python_Teaching/introduction/addition.py | 424 | 4.25 | 4 | def calc_addition(int_a,int_b):
""" Add the given two numbers """
try:
print (int(int_a) + int(int_b))
except ValueError:
print('You have to enter integers only!')
while True:
number_1 = input("Enter your first number: ")
number_2 = input("Enter your second number: ")
if (number_1 == 'quit') or (number_2 == 'quit'):
break
else:
calc_addition(number_1,number_2) | true |
e3c048c7444db6c50ada2f4ed8b4f2291e517443 | Divya-vemula/methodsresponse | /strings/dict.py | 699 | 4.59375 | 5 | # Creating, accessing and modifying a dictionary.
# create and print an empty dictionary
emptyDictionary = {}
print("The value of emptyDictionary is:", emptyDictionary)
# create and print a dictionary with initial values
grades = {"John": 87, "Steve": 76, "Laura": 92, "Edwin": 89}
print("\nAll grades:", grades)
# access and modify an existing dictionary
print("\nSteve's current grade:", grades["Steve"])
grades["Steve"] = 90
print("Steve's new grade:", grades["Steve"])
# add to an existing dictionary
grades["Michael"] = 93
print("\nDictionary grades after modification:")
print(grades)
# delete entry from dictionary
del grades["John"]
print("\nDictionary grades after deletion:")
print(grades) | true |
170d56e759e95b32561c83cbe3478684604ad616 | RoanPaulS/List_Python | /list_operations.py | 722 | 4.3125 | 4 | square = [1,2,3,4];
print(square);
print(square[0]);
square.append(0);
print(square);
square.append(121**2);
print(square);
print();
print();
# removing list elements
letter = ["a","b","c","d","e","f","g","a"];
print(letter);
print("Length is ",len(letter));
letter[2:5] = [];
print(letter);
print("Length is ",len(letter));
print();
print();
# finding length
alpha = ["a","b","c"];
num = [1,2,3];
both = alpha + num;
print("Both are : ",both);
print("Length is : ",len(both));
print();
both = [alpha , num];
print("Both are : ",both);
print("Length is : ",len(both));
print();
both = [alpha + num];
print("Both are : ",both);
print("Length is : ",len(both));
print();
| false |
4e52a490ec4ac9b4b8f07bda697464cd41a0476b | puthalalitha/calculator | /calculator.py | 1,990 | 4.3125 | 4 | """A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
# Your code goes here
# No setup
# repeat forever:
# read input
# tokenize input
# if the first token is "q":
# quit
# else:
# decide which math function to call based on first token
def calculator():
print("""Use spaces between answer
If adding use + (provide 2 numbers)
If subtracting use - (provide 2 numbers)
if mulitplication use * (provide 2 numbers)
if dividing use / (provide 2 numbers)
if squaring use square (provide 1 number)
if cubing use cube (provide 1 number)
if looking for remainder use mod (provide 2 numbers)
if power use pow (provide 2 numbers
if you want to quit press Q""")
while True:
user_input = input("What math function do you want? What are the numbers?: ")
user_words = user_input.split(" ")
if user_words[0] == "q":
break
else:
cal = user_words[0]
if cal == "cube" or cal == "square":
num1 = int(user_words[1])
if cal == "square":
print(square(num1))
elif cal == "cube":
print(cube(num1))
else:
num1 = int(user_words[1])
num2 = int(user_words[2])
if cal == "+" :
print(add(num1, num2))
elif cal == "-":
print(subtract(num1, num2))
elif cal == "*":
print(multiply(num1, num2))
elif cal == "/":
print(divide(num1, num2))
elif cal == "pow":
print(power(num1, num2))
elif cal == "mod":
print(mod(num1, num2))
calculator()
| true |
c13188089e7d5e6d3359d5f8642befcdfb2f1aed | Tarajit-Singh/python-lab-programs- | /5.1)experiment.py | 475 | 4.4375 | 4 | """
5.1) Implement a python script to count frequency of characters in a given string.
"""
s=input("enter the string")
result = {}
for letter in s:
if letter not in result:
result[letter.lower()] = 1
else:
result[letter.lower()] += 1
print("count frequency of characters in given string:",result)
#output
enter the string hello world
count frequency of characters in given string: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
| true |
130500eda364a84fa4398a12cd625bf5a832c4a1 | chasebleyl/ctci | /data-structures/interview-questions/arrays_and_strings/1_6.py | 1,808 | 4.125 | 4 | # String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
# O(N)
import unittest
def compress_string(string):
prev_char = string[0]
repeat_count = 1
compressed_chars = [string[0]]
for i in range(1, len(string)):
if string[i] == prev_char:
repeat_count += 1
else:
compressed_chars.append(str(repeat_count) + string[i])
repeat_count = 1
prev_char = string[i]
compressed_chars.append(str(repeat_count))
compressed_string = ''.join(compressed_chars)
if len(compressed_string) < len(string):
return compressed_string
return string
# First attempt, string concatenation is inefficient so needed to upgrade
# def compress_string(string):
# prev_char = string[0]
# repeat_count = 1
# compressed_string = string[0]
# for i in range(1, len(string)):
# if string[i] == prev_char:
# repeat_count += 1
# else:
# compressed_string += str(repeat_count) + string[i]
# repeat_count = 1
# prev_char = string[i]
# compressed_string += str(repeat_count)
# if len(compressed_string) < len(string):
# return compressed_string
# return string
class Test(unittest.TestCase):
'''Test Cases'''
data = [
('abbcccdddd', 'a1b2c3d4'),
('aabbccdd', 'aabbccdd'),
('aaAAAaa', 'a2A3a2'),
('abc', 'abc'),
]
def test_compress_string(self):
for [string, expected] in self.data:
result = compress_string(string)
self.assertEqual(result, expected)
if __name__ == "__main__":
unittest.main() | true |
eaa2834a381ad0a864cb9b5433d429ee183e0347 | osluocra/pachito_python | /code/s04/RosetteGoneWild.py | 457 | 4.15625 | 4 | # RosetteGoneWild.py
import turtle
t = turtle.Pen()
turtle.bgcolor('black')
t.speed(0)
t.width(3)
# Ask the user for the number of circles in their rosette, default to 6
number_of_circles = int(turtle.numinput("Number of circles",
"How many circles in your rosette?", 6))
color_of_circle = int(turtle.numinput("color of circle",
"What color do you want for first circle",blue)
| true |
0d764e769012d326598de8bdeb714a665cda1354 | sophiebuckley/cipher-project | /vigenerecipher.py | 2,035 | 4.625 | 5 | #A function which performs the Vigenere encryption algorithm on an input phrase.
key = raw_input("Please enter the keyword that you would like to use for your encryption: ")
message = raw_input("Please enter the message that you would like to encrypt: ")
def encrypt_vigenere(key, plaintext):
return vigenere_calc(key, plaintext, True)
def decrypt_vigenere(key, ciphertext):
return vigenere_calc(key, ciphertext, False)
def vigenere_calc(key, message, is_encrypt):
#Empty list to host results.
result = []
#Index to be used to cycle through letters.
alphabet_index = 0
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#Convert key input to all uppercase letters.
key = key.upper()
#For every letter in the message...
for symbol in message:
#... convert to uppercase version and find it's counterpart in the 'letters' list.
num = letters.find(symbol.upper())
#If this counterpart is not found (i.e. the input key is longer than 26 letters)...
if num != (-1):
#... cycle to the start of 'key'...
key_index = alphabet_index % len(key)
#... check whether to run the encryption or decryption algorithm.
if is_encrypt:
num += letters.find(key[key_index])
else:
num -= letters.find(key[key_index])
#... and cycle to the start of letters to continue assignment.
num = num % len(letters)
if symbol.isupper():
result.append(letters[num])
elif symbol.islower():
result.append(letters[num].lower())
print symbol, key[key_index], letters[num]
alphabet_index += 1
#Print all of the list items in 'letters' as a string.
print "".join(result)
return result
result = encrypt_vigenere(key, message)
prompt = raw_input("Would you like to decrypt a message? ")
if prompt == "Yes" or prompt == "yes":
decrypt_vigenere(key, result)
else:
exit()
| true |
d2ad9df2d675da2a918b47c296940014d44dfaaf | Keegan-Cruickshank/CP1404 | /prac_05/word_counter.py | 557 | 4.5625 | 5 | """
Simple application to display the frequency of all words from a users input.
"""
text_input = input("Text: ")
word_count_dict = {}
word_list = text_input.split(" ")
for word in word_list:
if word.lower() in word_count_dict:
word_count_dict[word.lower()] += 1
else:
word_count_dict[word.lower()] = 1
longest_word = 0
for word in word_count_dict:
if len(word) > longest_word:
longest_word = len(word)
for word, frequency in sorted(word_count_dict.items()):
print("{:{}} {}".format(word, longest_word, frequency))
| true |
fde1d6e88a167908ec38df2789a956294f4a8c92 | CristinaHG/python-Django | /python-Django/ExampleCourse/HelloWord.py | 1,072 | 4.3125 | 4 | # -*- coding: utf-8 -*-
print ("Hello World")
#collections and comments
#List
fruits=['Banana','Strawberry','Apple','Grapes']
print(fruits[0])
print(fruits[-1])
print(fruits[-3])
#List slicing
numbers=[0,1,2,3,4,5,6,7,8,9,10]
from_2to7=numbers[2:7]
print from_2to7
geatherThan3=numbers[3:]
print geatherThan3
pairsNumbers=numbers[::2]
print pairsNumbers
notpairNumbers=numbers[1::2]
print notpairNumbers
print (4 in numbers)
#dictionaries and None value
city={"name":'Granada',"place":"south","population":"12414112"}
print city["name"]#not a good way to acces dictionaries
print city.get("name")#GOOD WAY: return name or none if not found that key
#functions, brackets, :,;
#one instruction per line
#good code indent practice
def print_fruits(fruits):
for fruit in fruits:
print fruit
print_fruits(fruits)
#python 2 reads ASCII code by default
#print("Hola mundo rotísimo)" #syntax error: non-ASCII
#we can solve this by typing one of the "magic codification line":
# coding=utf-8
print("Hola mundo rotísimo")
#python interprets comments also!
| true |
f637759e6ebeac0ecc1bbb261f036568edad91d5 | adebudev/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 275 | 4.21875 | 4 | #!/usr/bin/python3
"""
function that reads a text file
"""
def read_file(filename=""):
"""
read_file - Read a text file
filename - Name of a File
"""
with open(filename, mode="r", encoding="utf-8") as file_open:
print(file_open.read(), end='')
| true |
d5c8046b9e8fa70ac2a690981311d8f29c89315c | heyjohnnie/MVA-Introduction-to-Python | /ShortStory/ShortStory/ShortStory/ShortStory.py | 792 | 4.4375 | 4 | #This program creates a short story based on user's input
#Welcome message
print("Welcome to Story Teller v1.0")
print("Let's create a short story where you'll be the main character!")
print("First, we need some info about you")
#Getting data and making sure to correct the input
firstName = " "
firstName = input("What's your first name? ")
firstName = firstName.capitalize()
lastName = " "
lastName = input("What's your last name? ")
lastName = lastName.capitalize()
location = " "
location = input("Where are you from? ")
location = location.capitalize()
age = input("How old are you? ")
print("This is the story of " + firstName + ", from the " + lastName + " lineage, first of his name.")
print("Who at the age of " + age + ", became hero of the sacred realm of " + location + ".") | true |
7256cea75dbad959fe52a797fa503fa3640b3c1e | mjruttenberg/battleships | /battleships_py3.py | 1,416 | 4.15625 | 4 | from random import randint
# create and populate the board
board = []
for x in range(5):
board.append(["O"] * 5)
# convert the board to space delimited and print the board
def print_board(board):
for row in board:
print(" ".join(row))
print_board(board)
# create the battleship X and Y axis positions randomly
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
#print("Ship row:)"+str(ship_row)
#print("Ship col:)"+str(ship_col)
# ask the user for a guess for X and Y axis
for turn in range(4):
print("Turn ", turn+1)
guess_row = int(input("Guess Row: "))
guess_col = int(input("Guess Col: "))
# check if hit/miss/off the board/previous guess
if guess_row == ship_row and guess_col == ship_col: # hit
print("\nCongratulations! You sank my battleship!")
break # end the for loop
elif guess_row < 0 or guess_row > 4 or guess_col < 0 or guess_col > 4:
print("\nOops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("\nYou guessed that one already.")
else:
print("\nYou missed my battleship!") # miss
board[guess_row][guess_col] = "X"
print_board(board)
# inform user that they are out of moves
if turn == 3:
print("\nGame Over") | true |
6ce4addde50d84d479b1d5e82cf6c5ea3c837013 | bmadren/MadrenMATH361B | /IntroToProgramming/I8_PrimeFunc_Madren.py | 494 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 20:58:00 2019
@author: benma
"""
def prime_check(N):
is_prime = True
if (N >= 2):
for i in range(2, N):
if((N % i) == 0 and N != i):
is_prime = False
else:
return False
return is_prime
n = 6
plist = []
count = 1
while(n >= len(plist)):
if(prime_check(count) == True):
plist.append(count)
count = count + 1
print("The ", n," prime number is ", plist[-2]) | false |
efc3b3713d3a98bac2f580bd7f55337485030f1f | deusdevok/pythonMergeSort | /mergeSort.py | 839 | 4.21875 | 4 | #######################
### MERGE ALGORITHM ###
#######################
import numpy as np
def mergesort (arr): # Sort array 'arr'
n = len(arr)
if (n == 1):
return arr
l1 = arr[0:int(n/2)]
l2 = arr[int(n/2):n]
l1 = mergesort(l1)
l2 = mergesort(l2)
return merge(l1,l2)
def merge (a,b): # Merge two lists
c = []
while (len(a)!=0 and len(b)!=0):
if (a[0] > b[0]):
c.append(b[0])
b.remove(b[0])
else:
c.append(a[0])
a.remove(a[0])
while (len(a)!=0):
c.append(a[0])
a.remove(a[0])
while (len(b)!=0):
c.append(b[0])
b.remove(b[0])
return c
a = -12.
b = 12.
N = 7
# Generates a random array of N elements between a and b
arr = np.random.rand(N)*(b-a) + a
arr=list(arr) # Generates a list from an array
print(arr)
print( mergesort(arr) )
| false |
492ad5738e83acdf1f4427af015eb9f95b3e597c | lion137/Functional---Python | /trees.py | 1,193 | 4.21875 | 4 | # define an abstract data - binary tree - pairs and functional abstraction
from functional_tools_python.immutable_lists import *
def construct_tree(val, left, right):
"""constructs a tree as a List, holds
as a first elem a value in a node, second and
third elements are left, right branches (also trees)"""
return List(val, left, right)
def value(tree):
"""returns a value holds in a tree node"""
return tree[0]
def left(tree):
"""returns a left branch of the tree"""
return tree[1]
def right(tree):
"""returns a right branch of the tree"""
return tree[2]
def contains_tree(a, tree):
"""check if tree contains an
elemnt a"""
if tree.is_empty():
return False
elif a == value(tree):
return True
elif a < value(tree):
return contains_tree(a, left(tree))
elif a > value(tree):
return contains_tree(a, right(tree))
if __name__ == '__main__':
tr1 = construct_tree(3, construct_tree(2, construct_tree(1, Nil(), Nil()), Nil()), construct_tree(4, Nil(), Nil()))
print(contains_tree(0, tr1)) # -> False
print(contains_tree(1, tr1)) # -> True
print(contains_tree(4, tr1)) # -> True
| true |
b520e97e73dd7cd2b9798ad22e3c6740286b913a | JustinDudley/Rubiks-Cube-One | /string_to_list.py | 1,239 | 4.4375 | 4 | # This module takes a Rubik's Cube algorithm, perhaps inputed by a user, and
# converts it to a list, so that it can be manipulated by other programs as a list
def convert_to_list(alg_stri):
# Takes a string and converts it to a list, for better functionality in manipulation by other programs.
# This function assumes it has been given a properly cleaned up algorithm.
alg_bare = alg_stri[:] # make a copy
alg_bare = alg_bare.replace("'", "")
alg_bare = alg_bare.replace("2", "")
# print(alg_bare)
alg_list = [] # Initialize
alg_stri += "9" # Creates dummy character at end of string, so that for-loop doesn't throw error on its final loop
for char in alg_bare: # says how many times I'm going to need to convert a portion of the string to an item of the list
if alg_stri[1] == "'":
alg_list.append(alg_stri[0] + "3")
alg_stri = alg_stri[2:] # first and second characters of string removed
elif alg_stri[1] == "2":
alg_list.append(alg_stri[0] + "2")
alg_stri = alg_stri[2:] # first and second characters of string removed
else:
alg_list.append(alg_stri[0] + "1")
alg_stri = alg_stri[1:] # only the first character of string removed
return alg_list
# print (convert_to_list("R'UF2R"))
| true |
dc7235719a4d37ae8dd3fff65023a67fa644d9a3 | Adam-Davey/cp1404_pracs | /prac_05/color_names.py | 497 | 4.21875 | 4 | COLOR_NAMES = {"turquoise": "#40e0d0", "yellowgreen": "#9acd32", "salmon": "#fa8072", "saddlebrown": "#8b4513"}
color_length = max([len(color) for color in COLOR_NAMES])
for color in COLOR_NAMES:
print("{:{}} is {}".format(color, (color_length), COLOR_NAMES[color]))
color = input("enter a color").lower()
while color != "":
if color in COLOR_NAMES:
print(color, "is", COLOR_NAMES[color])
else:
print("invalid color name")
color = input("enter a color").lower()
| true |
eb39963bd2f6cec6467103bc8be21bff19c1e762 | romannocry/python | /comparison.py | 535 | 4.4375 | 4 | # Python3 code to demonstrate
# set difference in dictionary list
# using list comprehension
# initializing list
test_list1 = ['ro','ma']
test_list2 = ['ro','man']
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using list comprehension
# set difference in dictionary list
res = [j for j in test_list2 if j not in test_list1]
# printing result
print ("The set difference of list is : " + str(res)) | true |
d5fa47b98d799059ac50cd3cdd6a4df0ca6c4f41 | reyllama/leetcode | /Python/C240.py | 1,603 | 4.125 | 4 | """
240. Search a 2D Matrix II
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
"""
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
def helper(i, j, target):
if i<len(matrix) and j<len(matrix[0]):
if matrix[i][j]==target:
return True
elif matrix[i][j]<target:
return helper(i+1,j,target) or helper(i,j+1,target)
else:
return False
return False
return helper(0,0,target)
"""
Time Limit Exceeded
"""
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m, n = len(matrix), len(matrix[0])
i, j = 0, n-1
while i<m and j>=0:
if matrix[i][j]==target:
return True
elif matrix[i][j]<target:
i += 1
else:
j -= 1
return False
"""
Runtime: 148 ms, faster than 24.04% of Python online submissions for Search a 2D Matrix II.
Memory Usage: 19.4 MB, less than 75.43% of Python online submissions for Search a 2D Matrix II.
""" | true |
0fa5eb00e017567a4be83ed88ffbc2b2bbdd2123 | reyllama/leetcode | /Python/#7.py | 847 | 4.15625 | 4 | '''
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
class Solution:
def reverse(self, x: int) -> int:
if x >= 0:
r = int(str(x)[::-1])
else:
r = -int(str(x)[1:][::-1])
return r if r in range(-2**31, 2**31) else 0
'''
Runtime: 20 ms, faster than 98.69% of Python3 online submissions for Reverse Integer.
Memory Usage: 13 MB, less than 99.34% of Python3 online submissions for Reverse Integer.
'''
| true |
d7240926fd437fd21e86fe98c928e1946d38cce3 | reyllama/leetcode | /Python/#344.py | 1,855 | 4.21875 | 4 | """
344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place
with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
i = 0
while i < len(s)-1:
if i==0:
s.append(s[0])
s.pop(0)
else:
s.insert(len(s)-i, s[0])
s.pop(0)
i += 1
"""
Runtime: 1156 ms, faster than 5.15% of Python3 online submissions for Reverse String.
Memory Usage: 18.1 MB, less than 95.68% of Python3 online submissions for Reverse String.
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
"""
Runtime: 284 ms, faster than 12.82% of Python3 online submissions for Reverse String.
Memory Usage: 18.4 MB, less than 23.22% of Python3 online submissions for Reverse String.
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
for i in range(len(s)//2):
t = s[i]
s[i] = s[len(s)-1-i]
s[len(s)-1-i] = t
"""
Runtime: 264 ms, faster than 15.35% of Python3 online submissions for Reverse String.
Memory Usage: 18 MB, less than 98.30% of Python3 online submissions for Reverse String.
"""
| true |
6996584587d1da1bea89feeac00a77acf8064f01 | reyllama/leetcode | /Python/C739.py | 1,665 | 4.1875 | 4 | """
739. Daily Temperatures
Given a list of daily temperatures temperatures, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures temperatures = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
"""
import collections
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
ans = [0] * len(temperatures)
memo = dict()
for i, v in enumerate(temperatures):
for key in memo.keys():
if memo[key] < v:
del memo[key]
ans[key] = i-key
memo[i] = v
return ans
"""
Time Limit Exceeded
"""
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
stack, ans = [], [0]*len(temperatures)
for i, v in enumerate(temperatures):
while stack and temperatures[stack[-1]] < v:
cur = stack.pop()
ans[cur] = i-cur
stack.append(i)
return ans
"""
Runtime: 452 ms, faster than 85.92% of Python online submissions for Daily Temperatures.
Memory Usage: 17.2 MB, less than 82.60% of Python online submissions for Daily Temperatures.
""" | true |
431b13b9f4000a3db036ff19a64714652560a1c6 | HaiyuLYU/UNSW | /COMP9021-Principles-of-Programming/Quizzes/Q6/quiz_6.py | 2,948 | 4.3125 | 4 | # Defines two classes, Point() and Triangle().
# An object for the second class is created by passing named arguments,
# point_1, point_2 and point_3, to its constructor.
# Such an object can be modified by changing one point, two or three points
# thanks to the method change_point_or_points().
# At any stage, the object maintains correct values
# for perimeter and area.
#
# Written by *** and Eric Martin for COMP9021
from math import sqrt
class PointError(Exception):
def __init__(self, message):
self.message = message
class Point():
def __init__(self, x = None, y = None):
if x is None and y is None:
self.x = 0
self.y = 0
elif x is None or y is None:
raise PointError('Need two coordinates, point not created.')
else:
self.x = x
self.y = y
# Possibly define other methods
class TriangleError(Exception):
def __init__(self, message):
self.message = message
class Triangle:
def __init__(self, *, point_1, point_2, point_3):
self.p1 = Point(point_1.x,point_1.y)
self.p2 = Point(point_2.x,point_2.y)
self.p3 = Point(point_3.x,point_3.y)
if self.p1.y!=0 and self.p2.y!=0 and self.p3.y!=0:
if(self.p1.x/self.p1.y)==(self.p2.x/self.p2.y)==(self.p3.x/self.p3.y):
raise TriangleError('Incorrect input, triangle not created.')
elif self.p1.y==0 and self.p2.y==0 and self.p3.y==0:
raise TriangleError('Incorrect input, triangle not created.')
a = sqrt((self.p1.x-self.p2.x)**2+(self.p1.y-self.p2.y)**2)
b = sqrt((self.p2.x-self.p3.x)**2+(self.p2.y-self.p3.y)**2)
c = sqrt((self.p1.x-self.p3.x)**2+(self.p1.y-self.p3.y)**2)
p = (a+b+c)/2
self.area =sqrt(p*(p-a)*(p-b)*(p-c))
self.perimeter = a+b+c
def change_point_or_points(self, *, point_1 = None,point_2 = None, point_3 = None):
if point_1 is not None:
self.p1 = point_1
if point_2 is not None:
self.p2 = point_2
if point_3 is not None:
self.p3 = point_3
flag = 0
if self.p1.y!=0 and self.p2.y!=0 and self.p3.y!=0:
if(self.p1.x/self.p1.y)==(self.p2.x/self.p2.y)==(self.p3.x/self.p3.y):
print('Incorrect input, triangle not modified.')
flag = 1
elif self.p1.y==0 and self.p2.y==0 and self.p3.y==0:
print('Incorrect input, triangle not modified.')
flag = 1
if flag ==0:
a = sqrt((self.p1.x-self.p2.x)**2+(self.p1.y-self.p2.y)**2)
b = sqrt((self.p2.x-self.p3.x)**2+(self.p2.y-self.p3.y)**2)
c = sqrt((self.p1.x-self.p3.x)**2+(self.p1.y-self.p3.y)**2)
p = (a+b+c)/2
self.area =sqrt(p*(p-a)*(p-b)*(p-c))
self.perimeter = a+b+c
# Possibly define other methods
| true |
cb3d396fef9475c46f6f01c3332647407ecacefb | Juli03b/coding | /python-ds-practice/fs_4_reverse_vowels/reverse_vowels.py | 819 | 4.25 | 4 | def reverse_vowels(s):
"""Reverse vowels in a string.
Characters which re not vowels do not change position in string, but all
vowels (y is not a vowel), should reverse their order.
>>> reverse_vowels("Hello!")
'Holle!'
>>> reverse_vowels("Tomatoes")
'Temotaos'
>>> reverse_vowels("Reverse Vowels In A String")
'RivArsI Vewols en e Streng'
reverse_vowels("aeiou")
'uoiea'
reverse_vowels("why try, shy fly?")
'why try, shy fly?''
"""
vowels = [vowel for vowel in s if vowel in 'aeiouAEIOU']
s = list(s)
vowels.reverse()
vowelsIdx = 0
for idx in range(len(s) - 1):
if s[idx] in 'aeiouAEIOU':
s[idx] = vowels[vowelsIdx]
vowelsIdx += 1
return ''.join(s)
print(reverse_vowels("Reverse Vowels In A String")) | false |
a252aaed19f3ab44a5366ab8022fbfe2787a6987 | MattB70/499-Individual-Git-Exercise | /DumbSort.py | 1,771 | 4.15625 | 4 | # Sorting Integers or Strings.
# Matthew Borle
# September 14, 2021
# Python 2.7.15
while True:
input_type = raw_input("Integers or Strings? (Ii/Ss): ")
if input_type == "I" or input_type == "i":
print "Integers selected"
array = raw_input("Input integers seperated by spaces:\n")
print "Input:\t" + array
array = array.split(" ")
array = [x for x in array if x.isdigit()] # remove any non numeric values
array.sort(key=int)
print "Output:\t" + " ".join(array)
break;
if input_type == "S" or input_type == "s":
print "Strings selected"
array = raw_input("Input strings seperated by spaces:\n")
print "Input:\t" + array
array = array.split(" ")
array = [x for x in array if not x.isdigit()] # remove any non string values
array.sort(key=str)
print "Output:\t" + " ".join(array)
break;
if input_type == "T" or input_type == "t": # Test
print "Tests selected"
print "String Input:\torange apple grape strawberry blackberry"
strings = "orange apple grape strawberry blackberry"
strings = strings.split(" ")
strings = [x for x in strings if not x.isdigit()] # remove any non string values
strings.sort(key=str)
print "String Output:\t" + " ".join(strings)
print "Integer Input:\t2 9 5 0 1 10 4 21 9 1"
integers = "2 9 5 0 1 10 4 21 9 1"
integers = integers.split(" ")
integers = [x for x in integers if x.isdigit()] # remove any non numeric values
integers.sort(key=int)
print "Integer Output:\t" + " ".join(integers)
break;
else: # User input invalid argument.
print "Invalid input type. Try again.\n"
| true |
3863f7eb7dd6770add7e38179e8cd7567db018fb | yangsg/linux_training_notes | /python3/basic02_syntax/datatype_list.py.demo/looping-techniques.py | 1,467 | 4.3125 | 4 | #// https://docs.python.org/3.6/tutorial/datastructures.html#looping-techniques
#// https://docs.python.org/3.6/library/functions.html
def iterate_dict():
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items(): #// 同时获取dict的key, value
print(k, v)
def iterate_list_with_index_value():
for i, v in enumerate(['tic', 'tac', 'toe']): #// 同时获取list的 index, value
print(i, v)
def iterate_multiple_list():
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers): #// 利用zip构造zip对象(提供类似一种元素为元组的list视图)
print('What is your {0}? It is {1}.'.format(q, a))
def iterate_in_reversed():
for i in reversed(range(1, 10, 2)): #// 反序迭代
print(i)
def iterate_with_sorted():
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)): #// 排序后迭代,注意:此例中使用了set去除重复,如果无需去重复,直接使用 sorted(basket) 即可
print(f)
#// demo01
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data: # 写在一行也可以:[value for value in raw_data if not math.isnan(value)]
if not math.isnan(value):
filtered_data.append(value)
filtered_data
| false |
7057b8a23fbfddadfae7d4e86db3428fae4c405d | yangsg/linux_training_notes | /python3/basic02_syntax/classes/02_a-first-look-at-classes.py | 2,324 | 4.625 | 5 |
#// https://docs.python.org/3.6/tutorial/classes.html#a-first-look-at-classes
#// 类定义需要先执行才能生效(可以将class 定义放在if 语句块或函数的内部)
if True:
class ClassInIfBlock():
pass
def function():
class ClassInFunction:
pass
#// 当进入 class definition 时,被当做 local scope的一个新的名字空间(namespace) 就被创建了
#// When a class definition is entered, a new namespace is created, and used as the local scope — thus,
#// all assignments to local variables go into this new namespace. In particular,
#// function definitions bind the name of the new function here.
#// When a class definition is left normally (via the end), a class object is created.
#// This is basically a wrapper around the contents of the namespace created by the class definition;
#// we’ll learn more about class objects in the next section. The original local scope
#// (the one in effect just before the class definition was entered) is reinstated,
#// and the class object is bound here to the class name given in the class definition header (ClassName in the example).
#// Class objects 支持两种类型的操作:成员引用 和 实例化
#// Class objects support two kinds of operations: attribute references and instantiation.
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
print(MyClass.i) #// 12345
print(MyClass.f) #// <function MyClass.f at 0x7efe4bb270d0>
MyClass.i = 7777
print(MyClass.i) #// 7777
print(MyClass.__doc__) #// A simple example class
#// 类的实例化,即创建一个属于该类的对象
x = MyClass() #// 有点类似于java 中的 'new MyClass()', 但是python中没有new关键字
#// python中的 __init__ 函数作用类似于 java中的构造器函数的作用
class ClassWithInitFunction():
def __init__(self): #// 带有 __init__ 初始函数的类, 每次实例化时会被自动调用
self.data = ['a', 'b']
x = ClassWithInitFunction()
print(x.data) #// ['a', 'b']
#// __init__ 函数接收参数的类
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print('x.r = {}, x.i = {}'.format(x.r, x.i)) #// x.r = 3.0, x.i = -4.5
| true |
0311b3f019f5296d2e4bf1e3084dd28d229dd452 | Pelinaslan/Cryptography | /Cryptology/Vigenere_cipher.py | 1,306 | 4.125 | 4 | import string
alphabet = string.ascii_uppercase
def Key_generation(text, key):
key = list(key)
if len(text) == len(key):
return (key)
else:
for i in range(len(text) - len(key)):
key.append(key[i % len(key)])
return key
def vigenere_Encryption(text, key):
encrypted_message =''
for i in range(len(text)):
encrypted_message += alphabet[(alphabet.index(text[i])
+ alphabet.index(key[i])) % 26]
print("The encrypted message is:", encrypted_message)
# original text
def vigenere_Decryption(cipher_text, key):
dencrypted_message = ''
for i in range(len(cipher_text)):
dencrypted_message += alphabet[(alphabet.index(cipher_text[i])
- alphabet.index(key[i]) +26) % 26]
print("The dencrypted message is:", dencrypted_message)
text = input("Your message:").upper()
keyword= input("Key:").upper()
key = Key_generation(text, keyword)
mood=False
while (mood==False):
x=int(input("Do you want to encrypt(1) or decrypt(2) your message?"))
if(x==1):
vigenere_Encryption(text,key)
mood=True
elif(x==2):
vigenere_Decryption(text,key)
mood=True
else:
print("Please enter a valid number..!")
| false |
31e193aaaeba31bf82941aa2da1dc1c1c17e58b8 | pxue/euler | /problem20.py | 2,910 | 4.1875 | 4 | # Problem20: Factorial digit sum
# find sum of factorial of 100!
# Python has builtin Math.Factorial function
# let's see how that's implemented
# From python src code
# Divide-and-conquer factorial algorithm
#
# Based on the formula and psuedo-code provided at:
# http://www.luschny.de/math/factorial/binarysplitfact.html
#
# Faster algorithms exist, but they're more complicated and depend on
# a fast prime factorization algorithm.
#
# Notes on the algorithm
# ----------------------
#
# factorial(n) is written in the form 2**k * m, with m odd. k and m are
# computed separately, and then combined using a left shift.
#
# The function factorial_odd_part computes the odd part m (i.e., the greatest
# odd divisor) of factorial(n), using the formula:
#
# factorial_odd_part(n) =
#
# product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
#
# Example: factorial_odd_part(20) =
#
# (1) *
# (1) *
# (1 * 3 * 5) *
# (1 * 3 * 5 * 7 * 9)
# (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
#
# Here i goes from large to small: the first term corresponds to i=4 (any
# larger i gives an empty product), and the last term corresponds to i=0.
# Each term can be computed from the last by multiplying by the extra odd
# numbers required: e.g., to get from the penultimate term to the last one,
# we multiply by (11 * 13 * 15 * 17 * 19).
#
# To see a hint of why this formula works, here are the same numbers as above
# but with the even parts (i.e., the appropriate powers of 2) included. For
# each subterm in the product for i, we multiply that subterm by 2**i:
#
# factorial(20) =
#
# (16) *
# (8) *
# (4 * 12 * 20) *
# (2 * 6 * 10 * 14 * 18) *
# (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
#
# The factorial_partial_product function computes the product of all odd j in
# range(start, stop) for given start and stop. It's used to compute the
# partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
# operates recursively, repeatedly splitting the range into two roughly equal
# pieces until the subranges are small enough to be computed using only C
# integer arithmetic.
#
# The two-valuation k (i.e., the exponent of the largest power of 2 dividing
# the factorial) is computed independently in the main math_factorial
# function. By standard results, its value is:
#
# two_valuation = n//2 + n//4 + n//8 + ....
#
# It can be shown (e.g., by complete induction on n) that two_valuation is
# equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
# '1'-bits in the binary expansion of n.
#/
# factorial_partial_product: Compute product(range(start, stop, 2)) using
# divide and conquer. Assumes start and stop are odd and stop > start.
# max_bits must be >= bit_length(stop - 2).
from math import factorial
print reduce(lambda x, y: x + y, [int(i) for i in str(factorial(100))])
| true |
f74dde0261038d46e3ada75c994c31d62ee9dba1 | rugbyprof/2143-ObjectOrientedProgramming | /ClassLectures/day01.py | 2,090 | 4.59375 | 5 | import random
# simple print!
print("hello world")
# create a list
a = []
# prints the entire list
print(a)
# adds to the end of the list
a.append(3)
print(a)
# adds to the end of the list
a.append(5)
print(a)
# adds to the end of the list, and python doesn't care
# what a list holds. It can a mixture of all types.
a.append("mcdonalds")
print(a)
# I can also append alist to a list.
# Lists of lists is how we represent multi-dimensional data (like 2D arrays)
a.append([1,2,3,'a','b'])
print(a)
s = "hello "
t = "world"
st = s + t
# python 'overloads' the `+` sign to perform a concetenation
# when adding strings.
print(st)
# simple loop that loops 10 times
# the 'range' function returns a 'list' in this case
# the list = [0,1,2,3,4,5,6,7,8,9]
for i in range(10):
# appand a random integer between 0 and 100
a.append(random.randint(0,100))
# This loop 'iterates' over the 'container' 'a' placing
# subsequent values in x
for x in a:
print(x)
# Another way of looping over a container (list).
# This has a more traditional c++ 'feel' to it.
for j in range(len(a)):
print(a[j])
print()
# print the last element in a list
print(a[len(a)-1])
# print the last element in a list (cooler way)
print(a[-1])
# Prints a "slice" of the list. In this case 2,3,4 (not 5).
print(a[2:5])
# Loop and jump by two's. Remember the range function takes different param numbers.
# 1. param = size of list to return
# 2. params = starting value, ending value that list will contain
# 3. params = same as 2. but adds an 'increment by' value as the third param
for i in range(0,len(a),2):
print(a[i])
print(a)
#Insert a value into a position in the list, without overwriting another value
a.insert(7,'dont jack my list')
# This would overwrite value at a[7]
# Or error if index did not exist
a[7] = 'dont jack my list'
print(a)
# Just like appending to the list
a.insert(len(a),'please work')
print(a)
# Should error, but defaults to appending to end of list
a.insert(len(a)+3,'hmmmm')
# prints second to last item
print(a[-2])
# errors
a[len(a)+2] = '999999'
| true |
165acb2cc72d57f0d8943f97abb0c7ce17f33b42 | yangreal1991/my_leetcode_solutions | /0035.search-insert-position/search-insert-position.py | 847 | 4.28125 | 4 | import numpy as np
class Solution:
def __init__(self):
pass
def searchInsert(self, nums, target):
"""Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
Args:
nums: List[int] -- a sorted array
target: int -- target value
Returns:
result: int -- the the index where it would be if it were inserted in order
"""
if len(nums) == 0:
return "Length of nums must be greater than 0."
for i, num in enumerate(nums):
if num >= target:
return i
return len(nums)
if __name__ == '__main__':
s = Solution()
nums = [1,3,5,6]
target = 5
print(s.searchInsert(nums, target))
| true |
0c3e6ac49b8bec6557523015348f8f6b3f04b09f | Kkkb/hello-world | /lpthw/ex6.py | 1,289 | 4.375 | 4 | # -- coding:utf-8 --
#Python通过双引号或单引号识别字符串
# 将变量x赋值给一个带有格式化字符串的字符串"There are %d types of people."
x = "There are %d types of people." % 10
# 将字符串"binary"赋值给变量binary
binary = "binary"
#变量do_not获得"don't"这个字符串
do_not = "don't"
# 1.变量y获得字符串"Those who know %s and those who %s.",带有两个格式化字符串,值为binary和do_not
y = "Those who know %s and those who %s." % (binary, do_not)
# 打印变量x
print x
# 2.输出变量y
print y
# 3.打印一个带有格式化字符的字符串,格式化字符的值为变量x
print "I said: %r." % x
# 4.打印一个带有格式化字符串的字符串,格式化字符的值为变量y
print "I also said: '%s'." % y
# 变量hilarious获得布尔值False
hilarious = False
# 变量joke_evaluation获得字符串"Isn't that joke so funny?! %r"
joke_evaluation = "Isn't that joke so funny?! %r"
# 打印joke_evaluation,其格式化字符串的值为hilarious
print joke_evaluation % hilarious
# 变量w获得字符串"This is the left side of..."
w = "This is the left side of..."
# 变量e获得字符串"a string with a right side."
e = "a string with a right side."
# 打印两字符串的和
print w + e | false |
f35131e969c63c6f09d2f5dade49e883ecceb3b0 | Kkkb/hello-world | /liaoxuefeng_python/recur_move.py | 392 | 4.125 | 4 | # -*- coding: utf-8 -*-
#汉诺塔的移动可以用递归函数非常简单地实现。
#请编写move(n, a, b, c)函数,它接收参数n,
#表示3个柱子A、B、C中第1个柱子A的盘子数量,
#然后打印出把所有盘子从A借助B移动到C的方法
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c) | false |
802fc59c09de89d9abaeff6326ef02d5dadf5777 | hahntech/python-practice | /subclasses.py | 1,080 | 4.28125 | 4 | #!/usr/bin/python3
class Animal:
"""A Loose Representation of an Animal"""
def __init__(self, animalType, name, breed):
self.animalType = animalType
self.name = name
self.breed = breed
self.age = 0
def birthDay(self):
self.age +=1
def getAge(self):
return self.age
def getName(self):
return self.name
class Dog(Animal):
"""A Loose Representation of a Dog"""
def __init__(self, name, breed):
Animal.__init__(self, "dog", name, breed)
class Cat(Animal):
"""A Loose Representation of a Cat"""
def __init__(self, name, breed):
Animal.__init__(self, "cat", name, breed)
if __name__ == '__main__':
qwerty = Dog("Qwerty", "German Shepperd")
while qwerty.getAge() < 9:
qwerty.birthDay()
raul = Cat("Raul", "Siamese")
while raul.getAge() < 3:
raul.birthDay()
print("My {}, {}, has {} years".format(qwerty.animalType, qwerty.getName(), qwerty.getAge()))
print("My {}, {}, has {} years".format(raul.animalType, raul.getName(), raul.getAge()))
| false |
d026133e160d8f0b83b5167fb1898c5334147cf4 | MattMackreth/BasicsDay1 | /02datatypes_strings.py | 1,689 | 4.59375 | 5 | # # Data types
# # Computers are stupid
# # they don't understand context so we need to be specific with data types
#
# # We can use type() to check datatypes
#
# # Strings
# # lists of characters bundled together in a specific order
# # using index
# print('hello')
# print(type('hello'))
#
# # Concatentation of strings
# string_a = 'hello there'
# name_person = 'Juan Pier'
# print(string_a + ' ' + name_person)
#
# # Useful methods
# # Length
# # Returns the length of a string
# print(len(string_a))
# print(len(name_person))
#
# # Strip
# # Removes trailing or prevailing white spaces
# string_num = ' 90383 '
# print(string_num)
# print(string_num.strip())
#
# # .Split this is a method for strings
# # it splits in a specific location and outputs a list (data type)
# string_text = 'Hello I need to test this'
# split_string = string_text.split(' ')
# print(split_string)
#
# # Capturing user input
# # get user input of first name
# # save user input to variable
# # get user last name and save it to variable
# # join the 2
# # print
#
# user_fname = input('What is your first name? ')
# user_lname = input('What is your last name? ')
# # Concatenation
# user_name = user_fname + ' ' + user_lname
# print('Hello ' + user_name)
# # Interpolation - use f in front of string to add python into the string
# welcome_message = f"Hi {user_name}, you are very welcome!"
# print(welcome_message)
# ctrl + / for mass comment out
# Count/Lower/Upper/Capitalize
text_example = "here is sOMe text wItH a whole bunch of lots of text, so much text wow"
# Count
print(text_example.count('e'))
print(text_example.upper())
print(text_example.capitalize())
print(text_example.lower())
# Casting
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.