blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
b78ec391ca8bbc6943de24f6b4862c8793e3cc14
|
cat-holic/Python-Bigdata
|
/03_Data Science/2.Analysis/3.Database/2.db_insert_rows.py
| 1,218
| 4.375
| 4
|
# 목적 : 테이블에 새 레코드셋 삽입하기
import csv
import sqlite3
# Path to and name of a CSV input file
input_file = "csv_files/supplier_data.csv"
con = sqlite3.connect('Suppliers.db')
c = con.cursor()
create_table = """CREATE TABLE IF NOT EXISTS Suppliers(
Supplier_Name VARCHAR(20),
Invoice_Number VARCHAR(20),
Part_Number VARCHAR(20),
Cost FLOAT,
Purchase_Date);"""
c.execute(create_table)
# Read the CSV file
# Insert the data into the Suppliers table
file_reader = csv.reader(open(input_file, 'r'), delimiter=',')
header = next(file_reader, None) # Header 건너뛰고 data만 접근 하기 위함
for row in file_reader:
data = []
for column_index in range(len(header)):
data.append(row[column_index])
print(data)
c.execute("INSERT INTO Suppliers VALUES (?,?,?,?,?);", data)
con.commit()
print("데이터 베이스 삽입 완료 \n\n")
# Query the Suppliers table
output = c.execute("SELECT * FROM Suppliers")
rows = output.fetchall()
for row in rows:
output = []
for column_index in range(len(row)):
output.append(row[column_index])
print(output)
| true
|
bea0678a341e3fc8bc10aeaa0f3f3ff5cce2eb43
|
akash3927/python-
|
/list.py
| 1,454
| 4.375
| 4
|
#lists
companies=["mahindra","swarajya","rucha","papl"]
#1
print(companies)
#2
print(companies[0])
#3
print(companies[1])
#4
print(companies[1].title())
#replacing
companies[0]="force"
print(companies)
#adding or appending
companies.append("mahindra")
print(companies)
#removing
del companies[0]
print(companies)
#sort
companies.sort()
print(companies)
######
print("Here is the original list:")
print(companies)
print("\nHere is the sorted list:")
print(sorted(companies))
print("\
nHere is the original list again:")
print(companies)
#reverse function
companies.reverse()
print(companies)
#length
print(len(companies))
####working with the lists
industries=["mahindra","swarajya","rucha","papl"]
for industry in industries:
print(industry)
print(industry.title()+",is good company for learning")
print("it s giving chance to freshers to built thier carrier")
##########or loop for numbers
for value in range(1,5):
print(value)
#######
numbers=list(range(1,6))
print(numbers)
#even numbers
evennos=list(range(2,40,2))
print(evennos)
####oddnos
oddnos=list(range(1,30,2))
print(oddnos)
####
nos=[1,2,3,4,5,6,7,8,9]
print(min(nos))
print(max(nos))
print(sum(nos))
####
squares=[square**2 for square in range(10,16)]
print(squares)
#####
family=["mother","father","brother","sister","me"]
print(family[1:4])
print(family[:4])
myfamily=family[:]
print(myfamily)
| false
|
13712aa9ee6581cdc87c817cb630001117e159b7
|
apriantoa917/Python-Latihan-DTS-2019
|
/LOOPS/loops - for examples.py
| 415
| 4.15625
| 4
|
#3.1.2.5 Loops in Python | for
# for range 1 parameter -> jumlah perulangan
for i in range(10) :
print("perulangan ke",i)
print()
# for range 2 parameter -> angka awal perulangan, angka akhir perulangan
a = 1
for i in range(3,10) :
print(i," = perulangan ke",a)
a+=1
print()
# for range 3 parameter -> angka awal, angka akhir, pertambahan / iterasi
for i in range(3,20,4) :
print(i)
print()
| false
|
e84ee8da19f091260bef637a5d7104b383f981a5
|
apriantoa917/Python-Latihan-DTS-2019
|
/LOOPS/loops - pyramid block.py
| 366
| 4.28125
| 4
|
# 3.1.2.14 LAB: Essentials of the while loop
blocks = int(input("Enter the number of blocks: "))
height = 0
layer = 1
while layer <= blocks:
blocks = blocks - layer #jumlah blok yang disusun pada setiap layer , 1,2,3...
height += 1 #bertambah sesuai pertambahan layer
layer += 1
print("The height of the pyramid:", height)
| true
|
a0eb44d5616b3d273426c5a7397c773a4a558c46
|
apriantoa917/Python-Latihan-DTS-2019
|
/TUPLES/tuples - example.py
| 691
| 4.21875
| 4
|
# 4.1.6.1 Tuples and dictionaries
# tuple memiliki konsep sama dengan list, perbedaan mendasar tuple dengan list adalah :
# Tuples
# - tuple menggunakan (), list menggunakan []
# - isi dari tuple tidak dapat dimodifikasi setelah di inisialisasi, tidak dapat ditambah (append) atau hapus (delete)
# - yang dapat dilakukan tuple :
# - len()
# - + (tambah), menambah elemen baru di dalam tuple (konsep append di list)
# - * (multiple), menggandakan isi tuple sejumlah n dengan isi yang sama
# - in, not in. sama dengan list
myTuple = (1, 10, 100)
t1 = myTuple + (1000, 10000)
t2 = myTuple * 3
print(len(t2))
print(t1)
print(t2)
print(10 in myTuple)
print(-10 not in myTuple)
| false
|
02fc00ec75f78c552b47cf4376c8d655b1012cc6
|
apriantoa917/Python-Latihan-DTS-2019
|
/LOOPS/loops - the ugly vowel eater.py
| 282
| 4.21875
| 4
|
# 3.1.2.10 LAB: The continue statement - the Ugly Vowel Eater
userWord = input("Enter the word : ")
userWord = userWord.upper()
for letter in userWord :
if (letter == "A" or letter == "I" or letter == "U" or letter == "E" or letter == "O"):
continue
print(letter)
| true
|
70320362f2dcf8277c59efd3a1b104fca0c0b784
|
100ballovby/6V_Lesson
|
/IV_term/05_lesson_2505/01_star_functions.py
| 1,387
| 4.3125
| 4
|
'''
Чтобы передать функции неограниченное количество элементов,
необходимо использовать звездочки.
*args - список аргументов
**kwargs - список именованных аргументов
На примере задачи. Дан список чисел, длина списка неизвестна,
сложите все числа в списке между собой. Верните сумму.
'''
from random import randint
n = []
for number in range(randint(1, 70)):
n.append(randint(-100, 100))
print(n)
def sum_list(*numbers):
'''Функция получает любое количество аргументов'''
print(type(numbers))
s = 0
for i in numbers:
s += i
return s
print(sum_list(4, 6, 7, 2)) # можно указывать любое количество чисел
print(sum_list(*n)) # распаковка списка (достать из него только числа и убрать скобки)
def smth(**kwargs):
'''Именованные аргументы в неограниченном количстве'''
print(type(kwargs))
print(kwargs)
for key, value in kwargs.items():
print(f'Key: {key}\nValue: {value}')
smth(name='Jagor', Age=26, Hobby='Programming', Pet='Cat')
| false
|
c73e20200d1fe03e2746432dc925cc63361fd5a4
|
100ballovby/6V_Lesson
|
/lesson_2601/task0.py
| 753
| 4.3125
| 4
|
'''
Task 0.
Систему работы с багажом для аэропорта.
Багаж можно поместить в самолет если:
Его ширина < 90 см;
Его высота < 80 см;
Его глубина < 40 см;
ИЛИ
Ширина + высота + глубина < 160.
'''
w = float(input('Введите ширину багажа: '))
h = float(input('Введите высоту багажа: '))
d = float(input('Введите глубину багажа: '))
if (w > 0 and h > 0 and d > 0) and ((w <= 90 and h <= 80 and d <= 40) or (w + h + d <= 160)):
print('Багаж можно поместить в самолет!')
else:
print('Багаж нельзя поместить в самолет!')
| false
|
fd09482d05ff8e7a0eebed43f3159153792a5834
|
100ballovby/6V_Lesson
|
/IV_term/03_lesson_0405/shapes.py
| 1,192
| 4.34375
| 4
|
'''
Параметры:
1. Черепашка
2. Длина стороны
3. координата х
4. координата у
5. Цвет
'''
def square(t, length, x, y, color='black'):
"""Функция рисования квадрата"""
t.goto(x, y) # переместить черепашку в x, y
t.down() # опустить перо (начать рисовать)
t.color(color) # задать черепашке цвет через параметр (по умолчанию - черный)
for i in range(4):
t.fd(length)
t.rt(90)
t.up() # поднять перо (перестать рисовать)
def triangle(t, length, x, y, thickness, color='black'):
t.goto(x, y)
t.pensize(thickness)
t.down()
t.color(color)
for i in range(3):
t.fd(length)
t.lt(120)
t.up()
t.pensize(1)
def rectangle(t, l1, l2, x, y, color='black'):
t.goto(x, y)
t.color(color)
t.down()
for i in range(2):
# рисую длинную сторону
t.fd(l1)
t.rt(90)
# рисую короткую сторону
t.fd(l2)
t.rt(90)
t.up()
| false
|
83c51994945f1fc21ad3cd97c257143b23604909
|
LukaszRams/WorkTimer
|
/applications/database/tables.py
| 1,559
| 4.15625
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file will store the data for the database queries that will be called to create the database
"""
# Table of how many hours an employee should work per month
class Monthly_working_time:
table_name = "MONTHLY_WORKING_TIME"
data = {
"id": ("integer", "PRIMARY KEY"),
"year": ("integer", "NOT NULL"),
"month": ("text", "NOT NULL"),
"hours": ("integer", "NOT NULL")
}
# A table that will contain data on the time worked by the employee during the month
class Working_time:
table_name = "WORKING_TIME"
data = {
"id": ("integer", "PRIMARY KEY"),
"user": ("text", "NOT NULL"),
"year": ("YEAR", "NOT NULL"),
"month": ("text", "NOT NULL"),
"total_hours": ("integer", "NOT NULL"), # number of hours worked by the employee
"base_hours": ("integer", "NOT NULL"), # the number of hours the employee was to work
"overtime_hours": ("integer", "NOT NULL"), # number of overtime hours
}
# Detailed data from employees' work, the amount of data grows very quickly so it needs to be cleaned
class Detailed_working_time:
table_name = "DETAILED_WORKING_TIME"
data = {
"id": ("integer", "PRIMARY KEY"),
"user": ("text", "NOT NULL"),
"date": ("DATE", "NOT NULL"), # detailed_working_time
"start_at": ("TIME", "NOT NULL"), # start time
"end_at": ("TIME", "NOT NULL"), # end time
}
tables = [Monthly_working_time, Working_time, Detailed_working_time]
| true
|
c6f55ab676a899e115bda4f5316e408f2710f1bd
|
Silentsoul04/FTSP_2020
|
/Extra Lockdown Tasks/Operators_Python.py
| 405
| 4.15625
| 4
|
# Operators in Python :-
1) Arithematic
2) Assignement
3) Comparison
4) Logical
5) Membership
6) Identity
7) Bitwise
Ex :-
x = 2
y = 3
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x//y)
print(x%y)
print(x**y)
Ex :-
x = 1001
print(x)
x+=9
print(x)
x-=9
print(x)
x*=9
print(x)
Ex :-
==
>
<
>= , <= , !=
x = 100
y = 500
print(x==y)
print(x<y)
print(y>x)
| false
|
928511975d3b85c7be7ed6c11c63ce33078cc5a1
|
Silentsoul04/FTSP_2020
|
/Python_CD6/reverse.py
| 874
| 4.25
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 11:41:04 2020
@author: Rajesh
"""
"""
Name:
Reverse Function
Filename:
reverse.py
Problem Statement:
Define a function reverse() that computes the reversal of a string.
Without using Python's inbuilt function
Take input from User
Sample Input:
I am testing
Sample Output:
gnitset ma I
"""
def reverse(x):
return x[: : -1]
x = input('Enter the string from user :')
print('The Reverse string :', reverse(x))
################ OR #################
def rev_string(str1):
return str1[: : -1]
str1 = input('Enter the string from user :')
print('The Reverse string :', rev_string(str1))
################ OR #################
def rev_num(num):
return num[: : -1]
num = input('Enter any number to reverse :')
print('The Reversed number :', rev_num(num))
| true
|
953ebb6e03cbac2798978798127e144ac2eee85f
|
Silentsoul04/FTSP_2020
|
/Python_CD6/generator.py
| 930
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 17:46:18 2020
@author: Rajesh
"""
"""
Name:
generator
Filename:
generator.py
Problem Statement:
This program accepts a sequence of comma separated numbers from user
and generates a list and tuple with those numbers.
Data:
Not required
Extension:
Not Available
Hint:
Not Available
Algorithm:
Not Available
Boiler Plate Code:
Not Available
Sample Input:
2, 4, 7, 8, 9, 12
Sample Output:
List : ['2', ' 4', ' 7', ' 8', ' 9', '12']
Tuple : ('2', ' 4', ' 7', ' 8', ' 9', '12')
"""
" NOTE :- split() function always split the given string and stored the values into list."
s = input('Enter some value :').split(',')
print('The List :', s)
print('The Tuple :', tuple(s))
############# OR ###############
str1 = input('enter any number :').split()
print('List :', str1)
print('Tuple :', tuple(str1))
| true
|
12430ff52d75dee8bae34b58f3a5164d585c4ec9
|
Silentsoul04/FTSP_2020
|
/Durga OOPs/Nested_Classes_OOPs.py
| 2,534
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 14 15:37:38 2020
@author: Rajesh
"""
Nested Classes :-
--------------
class Person:
def __init__(self):
self.name = 'Forsk Coding School'
self.dob = self.DOB()
def display(self):
print('Name :', self.name)
self.dob.display()
class DOB:
def __init__(self):
self.dd = 27
self.mm = 4
self.yyyy = 2018
def display(self):
print('Date of Birth :{}/{}/{}'.format(self.dd,self.mm,self.yyyy))
p = Person()
p.display()
*********** Result ************
Name : Forsk Coding School
Date of Birth :27/4/2018
---------------------------------------------------------------------------------------------------------
class Person:
def __init__(self,name,dd,mm,yyyy):
self.name = name
self.dob = self.DOB(dd,mm,yyyy)
def display(self):
print('Name :', self.name)
self.dob.display()
class DOB:
def __init__(self,dd,mm,yyyy):
self.dd = dd
self.mm = mm
self.yyyy = yyyy
def display(self):
print('Date of Birth :{}/{}/{}'.format(self.dd,self.mm,self.yyyy))
p1 = Person('Rajesh sharma',6,1,2020)
p2 = Person('Sandeep Jain',16,6,2019)
p3 = Person('Mohit Sharma',8,11,2015)
p1.display()
p2.display()
p3.display()
*********** Result ************
Name : Rajesh sharma
Date of Birth :6/1/2020
Name : Sandeep Jain
Date of Birth :16/6/2019
Name : Mohit Sharma
Date of Birth :8/11/2015
------------------------------------------------------------------------------------------------------------------
class Human:
def __init__(self):
self.name = 'Forsk coding school'
self.head = self.Head()
def display(self):
print('Name :',self.name)
self.head.talk()
self.head.brain.think()
class Head:
def __init__(self):
self.brain = self.Brain()
def talk(self):
print('Talking ........')
class Brain:
def think(self):
print('Thinking .........')
h = Human()
h.display()
*********** Result ************
Name : Forsk coding school
Talking ........
Thinking .........
-----------------------------------------------------------------------------------
| false
|
7ad064ce2fc4150f351ef3ce360dd3d7230a34f6
|
Silentsoul04/FTSP_2020
|
/Python_CD6/weeks.py
| 2,024
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 17:01:28 2020
@author: Rajesh
"""
"""
Name:
weeks
Filename:
weeks.py
Problem Statement:
Write a program that adds missing days to existing tuple of days
Sample Input:
('Monday', 'Wednesday', 'Thursday', 'Saturday')
Sample Output:
('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
"""
t = ('Monday', 'Wednesday', 'Thursday', 'Saturday')
l1=list(t) # Now Tuple will be converted into list and then we will be appending some of the values into it.
print('The tuple becomes into List : ', l1)
l1.append('Tuesday')
l1.append('Friday')
l1.append('Sunday')
print('The List after Adding some missing Items are :', l1)
t1 = tuple(l1)
sorted(t1)
print('The final output will be in Tuple only :', t1)
########### OR ##############
tuple = (10,20,30,40,50)
type(t)
list1 = list(tuple) # Now Tuple will be converted into list and then we will be appending some of the values into it.
print(list1)
list1.append(100)
list1.append(250)
list1.append(350)
print(list1)
for i in list1:
list2 = list1.count(i)
i+=1
print(list1)
list1.index(100)
list1.index(30)
list1.insert(5,0)
list1.insert(0,7)
list1.insert(2,450)
list1.remove(6) # We need to pass the particular element in list not index number. [ NOT Valid ]
list1.remove(0)
list1.pop()
print(list1)
list1.append(7)
list1.index(20)
list1.pop(3)
print(list1)
list2 = [] # Empty list.
print(list2) # It will be printing empty list.
list2.clear() # It is used to clear all the data from the list2.
print(list2)
list2.extend(list1) # It will be combining both lists each other.
list2.append(list1) # It will be combining list2 then whole list1 full without removing [] bracket like single character.
list1.sort()
list1.reverse()
print(type(t))
print(t)
print(t[0])
print(t[3])
print(t[-1])
print(t[:2])
t=() # Data type is empty tuple
t=(10,) # Single value tuple value always ends with comma ( ,).
| true
|
ce643b9df8113ce2ea53623aecf9d548398eea7e
|
Silentsoul04/FTSP_2020
|
/Durga Strings Pgms/Words_Str_Reverse.py
| 299
| 4.21875
| 4
|
# WAP to print the words from string in reverse order and take the input from string.
# s='Learning Python is very easy'
s=input('Enter some string to reverse :')
l=s.split()
print(l)
l1=l[: :-1] # The Output will be in the form of List.
print(l1)
output=' '.join(l1)
s.count(l1)
print(output)
| true
|
899db6e84ffad7514dbac57c7da77d04d78acb70
|
Silentsoul04/FTSP_2020
|
/Python_CD6/pangram.py
| 1,480
| 4.3125
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:37:41 2020
@author: Rajesh
"""
"""
Name:
Pangram
Filename:
pangram.py
Problem Statement:
Write a Python function to check whether a string is PANGRAM or not
Take input from User and give the output as PANGRAM or NOT PANGRAM.
Hint:
Pangrams are words or sentences containing every letter of the alphabet at least once.
For example: "the quick brown fox jumps over the lazy dog" is a PANGRAM.
Sample Input:
The five boxing wizards jumps.
Sphinx of black quartz, judge my vow.
The jay, pig, fox, zebra and my wolves quack!
Pack my box with five dozen liquor jugs.
Sample Output:
NOT PANGRAM
PANGRAM
PANGRAM
PANGRAM
"""
s = input('Enter any string :')
def Pangram():
str1 = 'abcdefghijklmnopqrstuvwxyz'
for i in str1:
if i in s:
if i == str1[-1]:
print('PANGRAM')
else:
print('NOT PANGRAM')
break
Pangram()
#################### OR ###########################
str1 = 'abcdefghijklmnopqrstuvwxyz'
inp = input(">>")
inpp = inp.split()
d = "".join(inpp)
x = sorted(d)
z= set(x)
x = list(z)
x1 = sorted(x)
z = "".join(x1)
if z == str1:
print("pangram")
else:
print("not pangram")
| true
|
f35d17401b20f52dd943239a2c40cb251fa53d03
|
jimkaj/PracticePython
|
/PP_6.py
| 342
| 4.28125
| 4
|
#Practice Python Ex 6
# Get string and test if palindrome
word = input("Enter text to test for palindrome-ness: ")
start = 0
end = len(word) - 1
while end > start:
if word[start] != word[end]:
print("That's not a palindrome!")
quit()
start = start + 1
end = end -1
print(word," is a palindrome!")
| true
|
668b160fffc014a4ef3996338f118fc9d4f1db6a
|
jimkaj/PracticePython
|
/PP_9.py
| 782
| 4.21875
| 4
|
# Practice Python #9
# Generate random number from 1-9, have use guess number
import random
num = random.randrange(1,10,1)
print('I have selected a number between 1 and 9')
print("Type 'exit' to stop playing")
count = 0
while True:
guess = input("What number have I selected? ")
if guess == 'exit':
break
count = count + 1
try: guess = int(guess)
except:
print("Invalid Input. You must input an integer or 'exit' to quit playing")
count = count -1
continue
if guess == num:
print('You guessed it! That took you',count,'tries')
exit()
if guess < num:
print('Too low! Guess again.')
if guess > num:
print('Too high! Guess again.')
| true
|
b1dff1aea71ec7ebfec48db1ec029a2a7dd349d2
|
artneuronmusic/Exercise2_SoftwareTesting
|
/app.py
| 1,673
| 4.15625
| 4
|
from blog import Blog
blogs = dict()
MENU_PROMPT = "Enter 'c' to create a blog, 'l' to list blog, 'r' to read one, 'p' to create a post, 'q' to quit"
POST_TEMPLATE = '''---{}---{}'''
def menu():
print_blogs()
selection = input(MENU_PROMPT)
while selection != 'q':
if selection == 'c':
create_blog()
elif selection == 'l':
print_blogs()
elif selection == 'r':
read_blog()
elif selection == 'p':
ask_create_post()
selection = input(MENU_PROMPT)
print_blogs()
def create_blog():
title = input("Whats the title of the post? ")
author = input("Who is the writer? ")
blogs[title] = Blog(title, author) #set the blogs as dict, then get value from blogs[key]
print(blogs[title])
def print_blogs():
for key, blog in blogs.items():
print("- {}".format(blog))
#print(key)
#print(blog)
def read_blog():
blog_title = input("Enter the blog title you want to read:")
for i in blogs[blog_title].posts:
try:
len(blogs[blog_title].posts) != 0
print(i)
except KeyError:
print("There is no such title")
"""
print_posts(blogs[blog_title])
def print_posts(blog):
for post in blog.posts:
print_post(post)
def print_post(post):
print(POST_TEMPLATE.format(post.name, post.content))
"""
def ask_create_post():
blog_name = input("Enter the blog title you want to write post in: ")
name = input("Whats the name of the post: ")
content = input("enter ur post content: ")
blogs[blog_name].create_post(name, content)
menu()
| false
|
9749245820a806a3da1f256446398a3558cabc6a
|
darthlyvading/fibonacci
|
/fibonacci.py
| 369
| 4.25
| 4
|
terms = int(input("enter the number of terms "))
n1 = 0
n2 = 1
count = 0
if terms <= 0:
print("terms should be > 0")
elif terms == 1:
print("Fibonacci series of ",terms," is :")
print(n1)
else:
print("Fibonacci series is :")
while count < terms:
print(n1)
total = n1 + n2
n1 = n2
n2 = total
count += 1
| true
|
5c96d7745ba921694275a5369cc4993c6bb5d023
|
inmank/SPOJ
|
/source/AddRev.py
| 2,292
| 4.3125
| 4
|
'''
Created on Jun 20, 2014
@author: karthik
The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies.
Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies.
Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites.
For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.
Reversed number is a number written in arabic numerals but the order of digits is reversed.
The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now.
Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21).
Also note that the reversed number never has any trailing zeros.
ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum.
Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing).
Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).
Input:
-----
The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases.
Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.
Output:
------
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.
Example
Sample input:
3
24 1
4358 754
305 794
Sample output:
34
1998
1
'''
def reverseNum(numIn):
numOut = 0;
while (numIn <> 0):
numOut = numOut * 10
numOut = numOut + numIn%10
numIn = numIn/10
return numOut
inCount = raw_input()
print inCount
for i in range(int(inCount)):
inValues = raw_input().split(" ")
print reverseNum(reverseNum(int(inValues[0])) + reverseNum(int(inValues[1])))
| true
|
4c209b1e3be29d2ec8c209911301b5930e3e2017
|
mozartfish/Summer_2019_Projects
|
/Linear Regression Algorithm/best_fit_line_intercept.py
| 964
| 4.1875
| 4
|
# this program explores writing a simple regression algorithm
# author: Pranav Rajan
# Date: June 10, 2019
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
# generate some random scattered data
xs = np.array([1, 2, 3, 4, 5, 6], dtype=np.float64)
ys = np.array([5, 4, 6, 5, 6, 7], dtype=np.float64)
# .scatter(xs, ys)
# plt.show()
def best_fit_slope(_and_interceptxs, ys):
m = (((mean(xs) * mean(ys)) - mean(xs * ys)) /
((mean(xs) * mean(xs)) - mean(xs * xs)))
b= mean(ys) - m * mean(xs)
return m, b
m, b = best_fit_slope(xs, ys)
regression_line = [(m * x) + b for x in xs]
# predict some future data points
predict_x = 7
predict_y = (m * predict_x) + b
print(predict_y)
predict_x = 7
predict_y = (m*predict_x)+b
plt.scatter(xs,ys,color='#003F72',label='data')
plt.plot(xs, regression_line, label='regression line')
plt.legend(loc=4)
plt.show()
# print(m, b)
| false
|
c95369771981b2f1a1c73b49a0156ede63aa3675
|
ginalamp/Coding_Challenges
|
/hacker_rank/arrays/min_swaps.py
| 1,383
| 4.34375
| 4
|
'''
Given an unsorted array with consecutive integers, this program
sorts the array and prints the minimum amount of swaps needed
to sort the array
'''
def main(arr):
'''
@param arr - an array of consecutive integers (unsorted)
@return the minimum amount of swaps needed to sort the given array
'''
# temp is an array where the values are the indexes
# If one accesses temp[val], one would get the index (i) as output
# The index in this case would be the expected value - 1
temp = {val: i for i, val in enumerate(arr)}
min_swaps = 0
for i in range(len(arr)):
value = arr[i]
# array contains consecutive integers starting from 1
expected_value = i + 1
# get the index of the value wanted
expected_i = temp[expected_value]
# swap values if not in the correct order
if value != expected_value:
# in the main array: swap current with the value wanted at the current index
arr[i] = expected_value
arr[expected_i] = value
# in the enum array: swap current with the value wanted at the current index
temp[value] = expected_i
temp[expected_value] = i
min_swaps += 1
print(min_swaps)
return min_swaps
if __name__ == '__main__':
arr = [1,3,5,2,4,6,7]
main(arr)
| true
|
340a802c8c77fdc2c4428926a8a2904fe8a388d0
|
chirag111222/Daily_Coding_Problems
|
/Interview_Portilla/Search/sequential_seach.py
| 513
| 4.15625
| 4
|
'''
Python => x in list --> How does it work?
Sequential Search
-----------------
'''
unorder = [4,51,32,1,41,54,13,23,5,2,12,40]
order = sorted(unorder)
def seq_search(arr,t):
found = False
for i in arr:
print(i)
if i == t:
found = True
return found
def ord_seq_search(arr,t):
for i in arr:
print(i)
if i == t:
return True
if i > t:
return False
return False
seq_search(unorder,3)
ord_seq_search(order,3)
| true
|
d9f9a0c1350d5d68c8e651a6c59b5f6cdd8bfbf1
|
chirag111222/Daily_Coding_Problems
|
/DailyCodingProblem/201_max_path_sum.py
| 1,816
| 4.125
| 4
|
'''
You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at a time to an adjacent value,
eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries.
Write a program that returns the weight of the maximum weight path.'''
# Could we gain something from moving it to a tree?
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
input = [[1], [2, 3], [1, 5, 1]]
'''
Approach:
Iterative calculate the max-cumulative sum at each node.
We are going to visit every node 1 time. O(N)
'''
import copy
cumulative_sum = copy.deepcopy(input)
for j in range(1,len(input)):
for i, entry in enumerate(input[j]):
print('\n\n{}'.format((j,i)))
print('cumulative_sum[{}][{}] += max(cumulative_sum[{}][max(0,{})], cumulative_sum[{}][min({},{})]'.format(
j,i,j-1,i-1,j-1,i,j-1))
print('N = {} + max({},{})'.format(
cumulative_sum[j][i], cumulative_sum[j-1][max(0,i-1)], cumulative_sum[j-1][min(i,j-1)] ))
cumulative_sum[j][i] += max(
cumulative_sum[j-1][max(0,i-1)],
cumulative_sum[j-1][min(i,j-1)] )
print(cumulative_sum)
def max_path(input):
depth = len(input)
for j in range(1,depth):
for i, entry in enumerate(input[j]):
input[j][i] += max(
input[j-1][max(0,i-1)],
input[j-1][min(i,j-1)] )
return max(input[j])
max_path(input)
| true
|
72cbfa9e3e72c688bf1f321b2e23d975f50fba79
|
silvium76/coding_nomads_labs
|
/02_basic_datatypes/1_numbers/02_04_temp.py
| 554
| 4.3125
| 4
|
'''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
temperature_fahrenheit = int(input("Please enter the temperature in Fahrenheit: "))
print(temperature_fahrenheit)
temperature_celsius = (temperature_fahrenheit - 32) * (5 / 9)
print(str(temperature_fahrenheit) + " degrees fahrenhei = " + str(temperature_celsius) + " degrees celsius ")
| true
|
e1b588a089bfc843ac186549b1763db5e55b70bd
|
umunusb1/PythonMaterial
|
/python3/02_Basics/02_String_Operations/f_palindrome_check.py
| 621
| 4.46875
| 4
|
#!/usr/bin/python3
"""
Purpose: Demonstration of Palindrome check
palindrome strings
dad
mom
Algorithms:
-----------
Step 1: Take the string in run-time and store in a variable
Step 2: Compute the reverse of that string
Step 3: Check whether both the strings are equal or not
Step 4: If equal, print that it is palindrome string
"""
test_string = input('Enter any string:')
print(test_string)
# reverse string
reverse_string = test_string[::-1]
print(reverse_string)
if test_string == reverse_string:
print( test_string, 'is palindrome')
else:
print( test_string, 'is NOT a palindrome')
| true
|
37b61ba736f127ebd0ef05a07a4b92b7311fae76
|
umunusb1/PythonMaterial
|
/python3/03_Language_Components/07_Conditional_Operations/b_number_guessing_game.py
| 790
| 4.1875
| 4
|
#!/usr/bin/python3
"""
Purpose: Number Guessing Game
"""
LUCKY_NUMBER = 69
given_number = int(input('Enter no. of between 0 & 100:'))
print(f'{LUCKY_NUMBER = }')
print(f'{given_number = }')
# print(f'{given_number == LUCKY_NUMBER =}')
# Method 1
# if given_number == LUCKY_NUMBER:
# print('You Guessed Correctly!')
# Method 2
# if given_number == LUCKY_NUMBER:
# print('You Guessed Correctly!')
# else:
# print('Please Try Again!!')
# Method 3
if given_number == LUCKY_NUMBER:
print('You Guessed Correctly!')
elif given_number > LUCKY_NUMBER: # 78 > 69
print('Please Try Again with reducing your guess number')
elif given_number < LUCKY_NUMBER: # 34 < 69
print('Please Try Again with increasing your guess number')
# NOTE: else block is optional in python
| false
|
400031d6d94eb77df6188d9ffb0ce00a31ba0ce9
|
umunusb1/PythonMaterial
|
/python2/03_Language_Components/05_Conditional_Operations/leap_year_check.py
| 1,282
| 4.40625
| 4
|
# Python program to check if the input year is a leap year or not
# year = 2018
# To get year (integer input) from the user
year = int(raw_input('year='))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
##################################################
if ((year % 4) == 0) and ((year % 100) == 0) and ((year % 400) == 0):
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
##################################################
if (not year % 4) and (not year % 100) and (not year % 400):
# 0 0 0
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
"""
>>>
>>> "{0} is a leap year".format('1998')
'1998 is a leap year'
>>> "{0} is a leap year".format(1998)
'1998 is a leap year'
>>> "{0} is a leap year".format(True)
'True is a leap year'
>>> "{0} is a leap {2}year{1}".format(True, 'vishnu', 1652)
'True is a leap 1652yearvishnu'
>>>
"""
| false
|
4bfc733c59848c52302a52b5366704fbedce4c94
|
umunusb1/PythonMaterial
|
/python3/04_Exceptions/13_custom_exceptions.py
| 564
| 4.15625
| 4
|
#!/usr/bin/python3
"""
Purpose: Using Custom Exceptions
"""
# creating a custom exception
class InvalidAge(Exception):
pass
try:
age = int(input('Enter your age:'))
age = abs(age)
if age < 18:
# raise InvalidAge('You are not eligible for voting')
raise InvalidAge(f'You are short by {18 - age} years for voting')
except InvalidAge as ex:
print(str(ex))
except ValueError:
print('Please enter valid age number')
except Exception as ex:
print('Unhandled Exception -', repr(ex))
else:
print('Eligible for voting!!!')
| true
|
e53448ad9ec7cd295a7570fc4e75187533c4c134
|
umunusb1/PythonMaterial
|
/python3/10_Modules/03_argparse/a_arg_parse.py
| 1,739
| 4.34375
| 4
|
#!/usr/bin/python
"""
Purpose: importance and usage of argparse
"""
# # Method 1: hard- coding
# user_name = 'udhay'
# password = 'udhay@123'
# server_name = 'issadsad.mydomain.in'
# # Method 2: input() - run time
# user_name = input('Enter username:')
# password = input('Enter password:')
# server_name = input('Enter server name:')
# # Method 3: sys.argv
# import sys
# print('sys.argv = ', sys.argv)
# assert sys.argv[0] == __file__
# # help
# if len(sys.argv) != 4:
# print('Help:')
# print(f'{__file__} username password server_fqdn')
# sys.exit(1)
# # user_name = sys.argv[1]
# # password = sys.argv[2]
# # server_name = sys.argv[3]
# # unpacking
# user_name, password, server_name = sys.argv[1:]
# Method 4: argparse
import argparse
parser = argparse.ArgumentParser(
description="Details to login to server",
epilog='-----Please follow help doc ----')
# description: for the text that is shown before the help text
# epilog: for the text shown after the help text
parser.add_argument('-u', '--username',
help='login user name',
type=str,
required=True)
parser.add_argument('-p', '--password',
help='login password',
type=str,
required=True)
parser.add_argument('-s', '--servername',
help='server name',
type=str,
default='www.google.com',
required=False)
args = parser.parse_args()
user_name = args.username
password = args.password
server_name = args.servername
print(f'''
The server login details are:
USER NAME : {user_name}
PASSWORD : {password}
SERVER NAME : {server_name}
''')
| true
|
f3665f6ae8aca1f6ad4017983ef50d681609809f
|
umunusb1/PythonMaterial
|
/python2/13_OOP/Practical/06_OOP.py
| 779
| 4.21875
| 4
|
#!/usr/bin/python
"""
Purpose: demo of OOP
"""
class Person:
def __init__(self): # constructor method
"""
This is constructor
"""
self.name = '' # instance variables
self.age = 0 # instance variables
def enter_age(self, age): # instance methods
self.age = age
def display_age(self): # instance methods
print('Person age is %d' % self.age)
def enter_name(self, name): # instance methods
self.name = name
def display_name(self): # instance methods
print('Person name is ' + self.name)
p = Person()
print(dir(p))
p.display_age()
p.enter_age(23)
p.display_age()
p.display_name()
p.enter_name('Ramesh')
p.display_name()
print callable(p.age)
print callable(p.display_age)
| false
|
2a202dd5ba552f4bda62adb4bfc92342d867d895
|
umunusb1/PythonMaterial
|
/python2/04_Collections/01_Lists/02_lists.py
| 1,791
| 4.59375
| 5
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
List can be classified as single-dimensional and multi-dimensional.
List is representing using [].
List is a mutable object, which means elements in list can be changed.
It can store asymmetric data types
"""
numbers = [88, 99, 666]
# homogenous
print 'type(numbers)', type(numbers)
print 'dir(numbers)=', dir(numbers)
print "len(numbers)=", len(numbers)
print "numbers.__len__()=", numbers.__len__()
print len(numbers) == numbers.__len__() # True
print "str(numbers) =", str(numbers)
print "type(str(numbers)) =", type(str(numbers))
print "numbers.__str__() =", numbers.__str__()
print "type(numbers.__str__())=", type(numbers.__str__())
# print "help(numbers)=", help(numbers)
print "numbers.__doc__=", numbers.__doc__
print "numbers * 3 =", numbers * 3 # original object not modified
print 'numbers =', numbers
print "numbers.__imul__(3) =", numbers.__imul__(3) # original object IS modified
print 'numbers =', numbers
print "id(numbers)=", id(numbers)
# object overwriting
numbers = [88, 99, 666]
print "id(numbers)=", id(numbers)
# list concatenation
print 'numbers\t\t\t\t=', numbers
alphabets = ['b', 'c']
print "numbers + alphabets\t\t=", numbers + alphabets
print 'numbers\t\t\t\t=', numbers
print "numbers.__add__(alphabets)\t=", numbers.__add__(alphabets)
print 'numbers\t\t\t\t=', numbers
# list concatenation will create new obect;
# orginal objects are not changed
print "numbers.__iadd__(alphabets)\t=", numbers.__iadd__(alphabets)
print 'numbers\t\t\t\t=', numbers # first object IS changed
print "numbers.__contains__(12) =", numbers.__contains__(12)
print "12 in numbers =", 12 in numbers
print numbers.__sizeof__()
# # print help(numbers.__sizeof__())
| true
|
7e83632d361b1ef09142d86fb45ec5584f8a12c2
|
umunusb1/PythonMaterial
|
/python2/02_Basics/01_Arithmetic_Operations/c_ArithmeticOperations.py
| 1,883
| 4.15625
| 4
|
#!/usr/bin/python
"""
Purpose: Demonstration of Arithmetic Operations
"""
# compound operators
# += -= *= /= %=
myNumber = 123
print 'myNumber = ', myNumber
myNumber = myNumber + 1
print 'myNumber = ', myNumber
# In cases, where the same variable is present both the sides, then compound operations are valid
myNumber += 1 # myNumber = myNumber + 1
print 'myNumber = ', myNumber
newNumber = 56
myNumber += newNumber + 1 # myNumber = myNumber + newNumber + 1
print 'myNumber = ', myNumber
myNumber -= 58 # myNumber = myNumber - 58
print 'myNumber = ', myNumber
myNumber *= 100 # myNumber = myNumber * 100
print 'myNumber = ', myNumber
myNumber /= 10 # myNumber = myNumber / 10
print 'myNumber = ', myNumber
myNumber %= 10 # myNumber = myNumber % 10
print 'myNumber = ', myNumber
# python dosnt support unary operations ; ++i, i++, --i, i--
# it should used as i += 1, i -=1
print '-----------------------------------------------'
print 'bitwise Operations'
# >> <<
myNewNumber = 4
print 'myNewNumber =', myNewNumber
myNewNumber <<= 1 # myNewNumber = myNewNumber << 1
print 'myNewNumber = ', myNewNumber
# 8 4 2 1
# 4 0 1 0 0 = 0 * 8 + 1 * 4 + 0 * 2 + 0 * 1 = 4
# << 1 0 0 0
# 13 1 1 0 1
# 7 0 1 1 1
# 15 1 1 1 1
result = 14 >> 2
print "14 >> 2 = ", result
# 8 4 2 1
# 14 1 1 1 0
# >>2 0 0 1 1
result = 3 << 2
print "3 << 2 = ", result
# 8 4 2 1
# 3 0 0 1 1
# <<2 1 1 0 0 => 12
calculated_result = 10 << 4
print '10 << 4', calculated_result
# 128 64 32 16 8 4 2 1
# 10 1 0 1 0
# 1 0 1 0 1st shift
# 1 0 1 0 2nd shift
# 1 0 1 0 3rd shift
# 1 0 1 0 4th shift
| false
|
f74b9eacbdbf872d13578b2802622482f5cf0f28
|
umunusb1/PythonMaterial
|
/python2/15_Regular_Expressions/re7/f1.py
| 274
| 4.1875
| 4
|
#!/usr/bin/python
import re
string = raw_input("please enter the name of the string:")
reg = re.compile('^.....$',re.DOTALL)
if reg.match(string):
print "our string is 5 character long - %s" %(reg.match(string).group())
else:
print "our string is not 5 characate long"
| true
|
b6330d881e53e6df85ec6e4a3e31822d8166252e
|
umunusb1/PythonMaterial
|
/python2/07_Functions/practical/crazy_numbers.py
| 832
| 4.65625
| 5
|
#!python -u
"""
Purpose: Display the crazy numbers
Crazy number: A number whose digits are when raised to the power of the number of digits in that number and then added and if that sum is equal to the number then it is a crazy number.
Example:
Input: 123
Then, if 1^3 + 2^3 + 3^3 is equal to 123 then it is a crazy number.
"""
def crazy_num(n):
a = b = int(n)
c = 0 # 'c' is the var that stores the number of digits in 'n'.
s = 0 # 's' is the sum of the digits raised to the power of the num of digits.
while a != 0:
a = int(a / 10)
c += 1
while b != 0:
rem = int(b % 10)
s += rem ** c
b = int(b / 10)
if s == n:
print ("Crazy number.")
else:
print ("Not crazy number.")
return None
n = int(input("Enter number: "))
crazy_num(n)
| true
|
e2bc5da0d4ce924d8bb9873a41a663d9b02d9618
|
umunusb1/PythonMaterial
|
/python2/02_Basics/01_Arithmetic_Operations/j_complex_numbers.py
| 964
| 4.375
| 4
|
#!/usr/bin/python
"""
Purpose: Demonstration of complex numbers
Complex Number = Real Number +/- Imaginary Number
In python, 'j' is used to represent the imaginary number.
"""
num1 = 2 + 3j
print "num1=", num1
print "type(num1)=", type(num1)
print
num2 = 0.0 - 2j
print "num2 = ", num2
print "type(num2) = ", type(num2)
print
print "num1 = ", num1
print "num1.conjugate() = ", num1.conjugate()
print "num1.real = ", num1.real
print "num1.imag = ", num1.imag
print
print "num1 * num2.real = ", num1 * num2.real
print "(num1*num2).real = ", (num1 * num2).real
# Observe the signs of imaginary numbers
print '========================================'
print 'arithmetic operations on complex numbers'
print '========================================'
print "num1 + num2 = ", num1 + num2
print "num1 - num2 = ", num1 - num2
print "num1 * num2 = ", num1 * num2
print "num1 / num2 = ", num1 / num2
print
print "num1 / 2 = ", num1 / 2
| false
|
3a9217c4b404d4a2ce236ca58b6fe60534bd0556
|
umunusb1/PythonMaterial
|
/python2/04_Collections/01_Lists/04_list.py
| 1,714
| 4.15625
| 4
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
mylist1 = [1, 11, 111, 1111]
print 'mylist1 = ', mylist1
print 'type(mylist1) = ', type(mylist1)
print
mylist2 = [2, 22, 222, 2222]
print 'mylist2 = ', mylist2
print 'type(mylist2) = ', type(mylist2)
print
newlist = mylist1 + mylist2
print 'newlist = ', newlist
print 'type(newlist) = ', type(newlist)
print
print 'mylist1.count(11):', mylist1.count(11)
print 'mylist1.count(2) :', mylist1.count(2)
# difference between list attributes: append and extend
print '=====mylist1.extend(mylist2)====='
mylist1.extend(mylist2)
print 'mylist1 = ', mylist1
print '=== reinitializing the list ==='
mylist1 = [1, 11, 111, 1111]
print '=====mylist1.append(mylist2)====='
mylist1.append(mylist2)
print 'mylist1 = ', mylist1
print '--- mylist1.append(9999)'
mylist1.append(9999)
print 'mylist1 = ', mylist1
# # Error --- extend can't take single element
# print '--- mylist1.extend(9999)'
# mylist1.extend(9999)
# # print 'mylist1 = ', mylist1
print
print '=== reinitializing the list ==='
mylist1 = [1, 11, 111, 1111]
print '--- mylist1.insert(0, mylist2)'
mylist1.insert(0, mylist2)
print 'mylist1 = ', mylist1
# difference between subsititution and insert
print '--- mylist1.insert(3, 99999)'
mylist1.insert(3, 99999)
print 'mylist1 = ', mylist1
print '--- mylist1[3] substitution'
mylist1[3] = 'Nine Nine Nine'
print 'mylist1 = ', mylist1
print
print '--- mylist1.insert(78, 5555555)'
mylist1.insert(78, 5555555)
print 'mylist1 = ', mylist1
# print '--- mylist1[89] substitution' # IndexError: list assignment index out of range
# mylist1[89] = 'Nine Nine Nine'
# print 'mylist1 = ', mylist1
| false
|
5ab99394f33b39ffeb47139e27ee740d5fc5bb2b
|
umunusb1/PythonMaterial
|
/python3/04_Exceptions/02_exceptions_handling.py
| 1,363
| 4.1875
| 4
|
#!/usr/bin/python3
"""
Purpose: Exception Handling
NOTE: Syntax errors cant be handled by except
"""
# import builtins
# print(dir(builtins))
num1 = 10
# num2 = 20 # IndentationError: unexpected indent
# for i in range(5):
# print(i) # IndentationError: expected an indented block
# 10 / 0 # ZeroDivisionError: division by zero
# 10 % 0 # ZeroDivisionError: integer division or modulo by zero
# 10 // 0 # ZeroDivisionError: integer division or modulo by zero
# num3 = int(input('Enter num:'))
# print(num3)
# # Method 1
# try:
# 10 / num3
# except:
# pass
# # Method 2
# try:
# 10 / num3
# except Exception as ex:
# print('ex :', ex)
# print('str(ex) :', str(ex))
# print('repr(ex):', repr(ex))
# print(f'{ex = }')
# Method 2 - example 2
try:
# 10 // 0 # ZeroDivisionError
# 10 / 0 # ZeroDivisionError
# 10 % 0 # ZeroDivisionError
10 + 0
# 10 + '0' # TypeError
# 10 + '0' # TypeError
# 10 + None # TypeError
float('3.1415')
# int('3.1415') # ValueError
name = 12123
name.upper() # AttributeError
except Exception as ex:
print('ex :', ex)
print('str(ex) :', str(ex))
print('repr(ex):', repr(ex))
print(f'{ex = }')
print('\nnext statement')
| false
|
dedb7dacef7ef63861c76784fc7cff84cf8ca616
|
umunusb1/PythonMaterial
|
/python3/10_Modules/09_random/04_random_name_generator.py
| 775
| 4.28125
| 4
|
from random import choice
def random_name_generator(first, second, x):
"""
Generates random names.
Arguments:
- list of first names
- list of last names
- number of random names
"""
names = []
for i in range(x):
names.append("{0} {1}".format(choice(first), choice(second)))
return set(names)
first_names = ["Drew", "Mike", "Landon", "Jeremy", "Tyler", "Tom", "Avery"]
last_names = ["Smith", "Jones", "Brighton", "Taylor"]
names = random_name_generator(first_names, last_names, 5)
print('\n'.join(names))
# Assignment:
# In runtime, take the gender name as input, and generate random name.
# HINT: Take a dataset of female first names, and another with male first names
# one dataset with last names
| true
|
8f6d1952edb0858a9f9c9b96c6719a1dd5fcb6d2
|
umunusb1/PythonMaterial
|
/python2/08_Decorators/06_Decorators.py
| 941
| 4.59375
| 5
|
#!/usr/bin/python
"""
Purpose: decorator example
"""
def addition(num1, num2):
print('function -start ')
result = num1 + num2
print('function - before end')
return result
def multiplication(num1, num2):
print('function -start ')
result = num1 * num2
print('function - before end')
return result
print addition(12, 34)
print multiplication(12, 34)
print '\n===USING DECORATORS'
def print_statements(func):
def inner(*args, **kwargs):
print('function -start ')
# print 'In print_statemenst decorator', func
myresult = func(*args, **kwargs)
print('function - before end')
return myresult
return inner
@print_statements
def addition11111(num1, num2):
result = num1 + num2
return result
@print_statements
def multiplication1111(num1, num2):
result = num1 * num2
return result
print multiplication1111(12, 3)
print addition11111(12, 34)
| true
|
df4858753ba98281c0dcef4e1cfc795d3e153ae3
|
OmishaPatel/Python
|
/miscalgos/reverse_integer.py
| 391
| 4.125
| 4
|
import math
def reverse_integer(x):
if x > 0:
x= str(x)
x = x[::-1]
x = int(x)
else:
x = str(-x)
x = x[::-1]
x = -1 * int(x)
if x <= math.pow(2, 31) -1 and x >= math.pow(-2,31):
return x
return 0
x = 123
x1 = -123
print(reverse_integer(x))
print(reverse_integer(x1))
| true
|
65ad7a18009d3595863f35760e7cc8f0ae78657d
|
OmishaPatel/Python
|
/datastructure/linked_list_insertion.py
| 1,290
| 4.3125
| 4
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self,data):
new_node = Node(data)
#if it is beginning of list then insert new node
if self.head is None:
self.head = new_node
return
#traverse the list if head present to find the last node
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self, prev_node, data):
if not prev_node:
print("Previous node not in the list")
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
linked_list = LinkedList()
linked_list.append("A")
linked_list.append("B")
linked_list.append("C")
linked_list.append("D")
linked_list.insert_after_node(linked_list.head.next, "E")
linked_list.print_list()
| true
|
3ba562ff4adaad94267aa9c62fdc1134d40b1910
|
ingoglia/python_work
|
/part1/4.11.py
| 326
| 4.1875
| 4
|
pizzas = ['anchovy', 'cheese', 'olive']
friend_pizzas = ['anchovy', 'cheese', 'olive']
pizzas.append('mushroom')
friend_pizzas.append('pineapple')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friends favorite pizzas are:")
for friend_pizza in friend_pizzas:
print(friend_pizza)
| false
|
3683f4b62501faa80cb0a67e3979cabe0fdc7e54
|
ingoglia/python_work
|
/part1/5.2.py
| 1,063
| 4.15625
| 4
|
string1 = 'ferret'
string2 = 'mouse'
print('does ferret = mouse?')
print(string1 == string2)
string3 = 'Mouse'
print('is a Mouse a mouse?')
print(string2 == string3)
print('are you sure? Try again')
print(string2 == string3.lower())
print('does 3 = 2?')
print(3 == 2)
print('is 3 > 2?')
print(3 > 2)
print('is 3 >= 2?')
print(3 >= 2)
print("I don't think that 8 = 4")
print(8 != 4)
print('is 6 <= 8?')
print(6 <= 8)
print('is 5 < 3?')
print(5 < 3)
religion1 = 'christian'
belief1 = 'god'
religion = 'religion'
belief = 'belief'
print( 'is it the case that a christian is both a deity and a believer?')
print( 'christian' == 'christian' and 'christian' == 'god' )
print( 'is it the case that a christian is either a deity or a believer?')
print( 'christian' == 'christian' or 'christian' == 'god' )
fruits = ['banana', 'blueberry', 'raspberry', 'melon']
print('is there a banana?')
print('banana' in fruits)
print('is there a raspberry?')
print('raspberry' in fruits)
print('there are no strawberries are there.')
print('strawberries' not in fruits)
| true
|
ebf65f149efb4a2adc6ff84d1dce2d2f61004ce4
|
ingoglia/python_work
|
/part1/8.8.py
| 633
| 4.375
| 4
|
def make_album(artist, album, tracks=''):
"""builds a dictionary describing a music album"""
if tracks:
music = {'artist': artist, 'album':album, 'number of tracks':tracks}
else:
music = {'artist': artist, 'album':album}
return music
while True:
print("\nPlease tell me an artist and an album by them:")
print("(enter 'q' at any time to quit)")
user_artist = input("Name of artist: ")
if user_artist == 'q':
break
user_album = input("Name of album: ")
if user_album == 'q':
break
user_choice = make_album(user_artist,user_album)
print(user_choice)
| true
|
b4a24b3ca29f09229589a58abfa8f0c9c4f3a094
|
marcellenoukimi/CS-4308-CPL-Assignment-3
|
/Student.py
| 2,681
| 4.34375
| 4
|
"""
Student Name: Marcelle Noukimi
Institution: Kennesaw State University
College: College of Computing and Software Engineering
Department: Department of Computer Science
Professor: Dr. Sarah North
Course Code & Title: CS 4308 Concepts of Programming Languages
Section 01 Fall 2021
Date: October 13, 2021
Assignment 3: Develop a Python program. Define a class in Python and use it to create an object
and display its components. Define a Student class with the following components (attributes):
Name
Student number
Number of courses current semester
This class includes several methods: to change the values of these attributes, and to display
their values. Separately, the “main program” must:
• request the corresponding data from input and create a Student object.
• invoke a method to change the value of one of its attributes of the object
• invoke a method to that displays the value of each attribute.
"""
"""
This is the Student class with its components (attributes):
Name
Student number
Number of courses current semester
and the several methods to change the values of these attributes,
and to display their values.
"""
class Student:
"""
Implementation of student class
"""
def __init__(self, name, studentNumber, numberOfCourses):
"""
Constructor. Each student holds a Name, a Student number,
and a number of courses that he/she is taken during
this semester
"""
# Name of the student
self.StudentName = name
# Student number
self.StudentNumber = studentNumber
# Number of courses current semester
self.NumberOfCourses = numberOfCourses
"""
Various setter methods
"""
# Method to change the value of a student name
def setStudentName(self, name):
self.StudentName = name
# Method to change the value of a student number
def setStudentNumber(self, number):
self.StudentNumber = number
# Method to change the value of a student number of courses
# for the current semester
def setStudentNumberOfCourses(self, courses):
self.NumberOfCourses = courses
"""
Method to display the value of each attribute of a student
"""
def display(self):
# Print student details information
return "Student Name: " + self.StudentName + "\n Student Number: " \
+ self.StudentNumber + "\n Number Of Courses taken the current semester: " + self.NumberOfCourses
| true
|
cd332ab59ede9fa70ac847d4dad76065aa9882a2
|
iNouvellie/python-3
|
/02_EstructuraDeDatos/06_Diccionario_III.py
| 594
| 4.375
| 4
|
calificaciones = {"tito": 10, "naty":6, "amaro": 5}
#Al recorrer e imprimir con un for, solo muestra la llave
for calificacion in calificaciones:
print (calificacion)
#De esta forma obtenemos el numero de la calificacion
for calificacion in calificaciones:
print (calificaciones[calificacion])
#Imprime la key, pero usando su metodo
for key in calificaciones.keys():
print (key)
#Imprime el value, pero usando su metodo
for value in calificaciones.values():
print (value)
#De esta forma obtenemos una tupla donde se muestra key y value
for item in calificaciones.items():
print (item)
| false
|
ebe0471563ed33d4af96c73109a0f83f33332ae4
|
iNouvellie/python-3
|
/01_IntroduccionPython/07_Ciclos.py
| 697
| 4.125
| 4
|
#Ciclos while, repiten bloque de codigo mientras la condicion sea cierta
#Ciclo for, recorren elementos en una coleccion
frutas = 10
while frutas > 0:
print ("Estoy comiendo una fruta " + str(frutas))
#frutas = frutas - 1
frutas -= 1
if frutas == 0:
print ("\n")
print ("Me quede sin frutas")
#--- o ---
lista_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for numero in lista_nums:
#Palabras reservadas continuo y break
#Break rompe ciclo si se llega a dicha condicion
if numero > 5:
break
print (numero)
print ("\n")
for numero in lista_nums:
#Palabras reservadas continuo y break
#Continuo salta la itereacion si cumple dicha condicion
if numero == 5:
continue
print (numero)
| false
|
51e015545046b6411f88bcf969c22b69529464d3
|
bigmoletos/WildCodeSchool_France_IOI-Sololearn
|
/soloearn.python/sololearn_pythpn_takeAshortCut_1.py
| 1,353
| 4.375
| 4
|
#Quiz sololearn python test take a shortcut 1
#https://www.sololearn.com/Play/Python
#raccouri level1
from _ast import For
x=4
x+=5
print (x)
#*************
print("test 2")
#What does this code do?
for i in range(10):
if not i % 2 == 0:
print(i+1)
#*************
print("test 3")
#What is the output of this code?
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
#*************
print("test 4")
#What does this code output?
letters = ['x', 'y', 'z']
letters.insert(1, 'w')
print(letters[2])
#*************
print("test 6")
#How many lines will this code print?
while False:
print("Looping...")
#*************
print("test 7")
#Fill in the blanks to define a function that takes two numbers as arguments and returns the smaller one.
def min(x, y):
if x<=y:
return x
else:
return y
#*************
print("test 8")
#Fill in the blanks to iterate over the list using a for loop and print its values.
list = [1, 2, 3]
for var in list:
print(var)
#*************
print("test 9")
#Fill in the blanks to print the first element of the list, if it contains even number of elements.
list = [1, 2, 3, 4]
if len(list) % 2 == 0:
print(list[0])
#*************
print("test 10")
#What is the output of this code?
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(5))
| true
|
d1349d0982af9e06c5e8c5aaa26b200497b22e3f
|
guokairong123/PythonBase
|
/DataStructure/list_demo1.py
| 663
| 4.1875
| 4
|
"""
如果我们想生产一个平方列表,比如 [1, 4, 9...],使用for循环应该怎么写,使用列表推导式又应该怎么写呢?
"""
# list_square = []
# for i in range(1, 4):
# list_square.append(i**2)
# print(list_square)
#
# list_square2 = [i**2 for i in range(1, 4)]
# print("list_suqare2:", list_square2)
#
# list_square3 = [i**2 for i in range(1, 4) if i != 1]
# # for i in range(1, 4):
# # if i!=1:
# # list_square3.append(i**2)
# print(list_square3)
list_square4 = [i*j for i in range(1, 4) for j in range(1, 4)]
# for i in range(1, 4):
# for j in range(1, 4):
# list_square4.append(i*j)
print(list_square4)
| false
|
da0cd5a8d5ed63e56893410eec04ab7eb3df7cff
|
ARCodees/python
|
/Calculator.py
| 458
| 4.21875
| 4
|
print("this is a calculator It does all oprations but only with 2 numbers ")
opration = input("Enter your opration in symbolic way ")
print("Enter Your first number ")
n1 = int(input())
print("Enter Your second number ")
n2 = int(input())
if opration == "+":
print(n1 + n2)
elif opration == "-":
print(n1 - n2)
elif opration == "*":
print(n1 * n2)
elif opration == "/":
print(n1 / n2)
else:
print("illogical Input!!")
| true
|
b9e6f248199d58f6f185160a24febe997becf9e0
|
Kwon1995-2/BC_Python
|
/chapter4/problem3.py
| 564
| 4.46875
| 4
|
"""3명 이상의 친구 이름 리스트를 작성하고
insert()로 맨 앞에 새로운 친구 추가
insert()로 3번째 위치에 새로운 친구 추가
append()로 마지막에 친구추가
"""
friend = ["A","B","C"]
friend.insert(0,"D") #
friend.insert(3,"E")
print(friend)
friend.insert(100, "X") #append와 비슷한 기능
friend.append('a')
print(friend)
# numli = [1,2,3]
# numli.insert(1,17)
# print(numli)
# numli.append(4)
# numli.append(5)
# numli.append(6)
# numli.insert(3,25)
# del(numli[0])
# numli.pop(0)
# print(numli)
| false
|
797cdc5d2c7d19a64045bc0fc1864fcefe0633b4
|
carlmcateer/lpthw2
|
/ex4.py
| 1,065
| 4.25
| 4
|
# The variable "car" is set to the int 100.
cars = 100
# The variable "space_in_a_car" is set to the float 4.0.
space_in_a_car = 4
# The variable "drivers" is set to the int 30.
drivers = 30
# The variable "passengers" is set to the int 90.
passengers = 90
# The variable cars_not_driven is set to the result of "cars" minus "drivers"
cars_not_driven = cars - drivers
# The variable "cars_driven" is set to the variable "drivers"
cars_driven = drivers
# The variable "carpool_capacity" is set to "cars_driven" times "space_in_a_car"
carpool_capacity = cars_driven * space_in_a_car
# The variable "average_passengers_per_car" is set to "passengers" devided by "cars_driven"
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars avaiable."
print "There are only", drivers, "drivers avaiable."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
| true
|
093233f29bfc50e37eb316fdffdf3a934aa5cea3
|
manasjainp/BScIT-Python-Practical
|
/7c.py
| 1,470
| 4.40625
| 4
|
"""
Youtube Video Link :- https://youtu.be/bZKs65uK1Eg
Create a class called Numbers, which has a single class attribute called
MULTIPLIER, and a constructor which takes the parameters x and y (these should
all be numbers).
i. Write a method called add which returns the sum of the attributes x and y.
ii. Write a class method called multiply, which takes a single number
parameter a and returns the product of a and MULTIPLIER.
iii. Write a static method called subtract, which takes two number parameters, b
and c, and returns b - c.
iv. Write a method called value which returns a tuple containing the values of x
and y. Make this method into a property, and write a setter and a deleter for
manipulating the values of x and y.
Save File as 7c.py
Run :- python 7c.py
"""
class Numbers:
MULTIPLIER=5
def __init__(self,x,y):
self.x=x
self.y=y
#subpart-1
def add(self):
return self.x + self.y
#subpart-2
@classmethod
def multiply(cls,a):
return cls.MULTIPLIER * a
#subpart-3
@staticmethod
def substract(b,c):
return b-c
#subpart-4
@property
def value(self):
return(self.x, self.y)
@value.setter
def value(self, t):
self.x = t[0]
self.y = t[1]
@value.deleter
def value(self):
self.x=None
self.y=None
ob=Numbers(10,20)
print("Add :- ",ob.add())
print("Multiply :- ", Numbers.multiply(10))
print("Substract :- ", Numbers.substract(20,10))
ob.value=(100,200)
print("Add :- ", ob.add())
del ob.value
print("Values :- ",ob.value)
| true
|
d916840b3ec5c3efbb4ee0b1c1aea1ad42844d66
|
omushpapa/minor-python-tests
|
/Large of three/large_ofThree.py
| 778
| 4.40625
| 4
|
#!/usr/bin/env python2
#encoding: UTF-8
# Define a function max_of_three()
# that takes three numbers as arguments
# and returns the largest of them.
def max_of_three(num1, num2, num3):
if type(num1) is not int or type(num2) is not int or type(num3) is not int:
return False
num_list = [num1, num2, num3]
temp = 0
if num1 == num2 == num3:
return num3
for i in range(len(num_list) - 1):
if num_list[i] < num_list[i + 1]:
temp = num_list[i + 1]
return temp
def main():
value1 = input("Enter first value: ")
value2 = input("Enter second value: ")
value3 = input("Enter third value: ")
print max_of_three(value1, value2, value3)
if __name__ == "__main__":
print "Hello World"
| true
|
e6134ced3a1fc1b67264040e64eba2af21ce8e1d
|
omushpapa/minor-python-tests
|
/List Control/list_controls.py
| 900
| 4.15625
| 4
|
#!/usr/bin/env python2
#encoding: UTF-8
# Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10, and
# multiply([1, 2, 3, 4]) should return 24.
def sum(value):
if type(value) is not list:
return False
summation = 0
for i in value:
if type(i) is not int:
return False
summation = summation + i
return summation
def multiply(value):
if type(value) is not list:
return False
result = 1
for i in value:
if type(i) is not int:
return False
result = result * i
return result
def main():
ans = input("Enter values in list: ")
print sum(ans)
print multiply(ans)
if __name__ == "__main__":
main()
| true
|
6c58ca9f940f7ab15d3b99f27217b3bd485b01f9
|
omushpapa/minor-python-tests
|
/Operate List/operate_list.py
| 1,301
| 4.1875
| 4
|
# Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is None:
return False
if len(num_list) == 0:
return False
new_list = []
for i in num_list:
if i!='[' and i!=']' and i!=',':
new_list.append(i)
for x in new_list:
if type(x) != int:
return False
return True
def sum(num_list):
"""Compute sum of list values"""
if check_list(num_list):
final_sum = 0
for i in num_list:
final_sum = final_sum + i
return final_sum
else:
return False
def multiply(num_list):
"""Multiply list values"""
if check_list(num_list):
final_sum = 1
for i in num_list:
final_sum = final_sum * i
return final_sum
else:
return False
def main():
get_list = input("Enter list: ")
operations = [sum, multiply]
print map(lambda x: x(get_list), operations)
if __name__ == "__main__":
main()
| true
|
a193124758fc5b01168757d0f98cf67f9b98c664
|
omushpapa/minor-python-tests
|
/Map/maps.py
| 388
| 4.25
| 4
|
# Write a program that maps a list of words
# into a list of integers representing the lengths of the correponding words.
def main():
word_list = input("Enter a list of strings: ")
if type(word_list) != list or len(word_list) == 0 or word_list is None:
print False
else:
print map(lambda x: len(x), word_list)
if __name__ == "__main__":
main()
| true
|
b0956c92848ea9087b83181d0dfcd360e45bdade
|
hubieva-a/lab4
|
/1.py
| 718
| 4.4375
| 4
|
# Дано число. Вывести на экран название дня недели, который соответствует
# этому номеру.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
n = input("Number of the day of the week")
n = int(n)
if n == 1:
print("Monday")
elif n== 2:
print("Tuesday")
elif n == 3:
print("Wednesday")
elif n == 4:
print("Thursday")
elif n == 5:
print("Friday")
elif n == 6:
print("Saturday")
elif n == 7:
print("Sunday")
else:
print("Please choose a number in range from 1 to 7")
exit(1)
| false
|
96f5fbe27bf7bd62b365d50f0266ce8297042094
|
amanotk/pyspedas
|
/pyspedas/dates.py
| 1,592
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
File:
dates.py
Description:
Date functions.
"""
import datetime
import dateutil.parser
def validate_date(date_text):
# Checks if date_text is an acceptable format
try:
return dateutil.parser.parse(date_text)
except ValueError:
raise ValueError("Incorrect data format, should be yyyy-mm-dd: '"
+ date_text + "'")
def get_date_list(date_start, date_end):
"""Returns a list of dates between start and end dates"""
d1 = datetime.date(int(date_start[0:4]), int(date_start[5:7]),
int(date_start[8:10]))
d2 = datetime.date(int(date_end[0:4]), int(date_end[5:7]),
int(date_end[8:10]))
delta = d2 - d1
ans_list = []
for i in range(delta.days + 1):
ans_list.append(str(d1 + datetime.timedelta(days=i)))
return ans_list
def get_dates(dates):
"""Returns a list of dates
date format: yyyy-mm-dd
input can be a single date or a list of two (start and end date)
"""
ans_list = []
if not isinstance(dates, (list, tuple)):
dates = [dates]
if len(dates) == 1:
try:
validate_date(dates[0])
ans_list = dates
except ValueError as e:
print(e)
ans_list = []
elif len(dates) == 2:
try:
validate_date(dates[0])
validate_date(dates[1])
ans_list = get_date_list(dates[0], dates[1])
except ValueError as e:
print(e)
ans_list = []
return ans_list
| true
|
5e0ca56488a3cda328eb88bd0a1fdd7ba6cb2bb8
|
sreckovicvladimir/hexocin
|
/sqlite_utils.py
| 1,702
| 4.125
| 4
|
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
sql = """ CREATE TABLE IF NOT EXISTS data_points (
n integer NOT NULL,
p integer NOT NULL,
data text NOT NULL
); """
try:
c = conn.cursor()
c.execute(sql)
except Error as e:
print(e)
def populate_table(conn, row):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
sql = ''' INSERT INTO data_points(n,p,data)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, row)
conn.commit()
return cur.lastrowid
def select_row(conn, n, p):
"""
Return single row from data_points table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT data FROM data_points where n=%d and p=%d" % (n, p))
query = cur.fetchone()
if query == None:
raise ValueError("Something went wrong, probably arguments out of range or the db isn't properly populated")
return query[0]
| true
|
04da350a513c7cc103b948765a1a24b9864686e1
|
JayHennessy/Stack-Skill-Course
|
/Python_Intro/pandas_tutorial.py
| 631
| 4.28125
| 4
|
# Python Pandas tutorial (stackSkill)
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
data = pd.read_csv('C:/Users/JAY/Desktop/Machine_Learning_Course/KaggleCompetions/titanic_comp/data/test.csv')
# shows data on screen
print(data.head())
data.tail()
#print the number of rows (incldues the header)
print(len(data.index))
# return rows that meet a certain condition
# here we get the date value for all the days that have rain in the event column
rainy_days = data['Date'][df['Events']=='Rain']
# plot the results with matplotlib
style.use('classic')
data['Max.TemperatureC'].plot()
plt.show()
| true
|
f62bd2ec440e3929c5aee99d0b90fd726e3f3eff
|
aniket0106/pdf_designer
|
/rotatePages.py
| 2,557
| 4.375
| 4
|
from PyPDF2 import PdfFileReader,PdfFileWriter
# rotate_pages.py
"""
rotate_pages() -> takes three arguements
1. pdf_path : in this we have to pass the user pdf path
2. no_of_pages : in this we have to pass the number of pages we want to rotate if all then by
default it takes zero then we re-intialize it to total number of pages
3. clockwise : it is default args which take boolean value if its value is True then it
will right rotate by given angle
if it is false then it will rotate towards the left by given angle
getNumPages() : is the function present in the PyPDF2 which is used to get the total number
of page present inside the inputted pdf
getPage(i) : is the function which return the particular page for the specified pdf
rotateClockwise(angle) : is the function which rotate the specified page by given angle
towards to right
rotateCounterClockwise(angle) : is the function which rotate the specified page by given angle
towards the left
"""
def rotate_pages(pdf_path,no_of_pages=0,clockwise=True):
# creating the instance of PdfFileWriter we have already initialize it with our output file
pdf_writer = PdfFileWriter()
pdf_reader = PdfFileReader(pdf_path)
total_pages = pdf_reader.getNumPages()
if no_of_pages == 0:
no_of_pages = total_pages
if clockwise:
for i in range(no_of_pages):
page = pdf_reader.getPage(i).rotateClockwise(90)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
for i in range(no_of_pages,total_pages):
page = pdf_reader.getPage(i)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
else:
for i in range(no_of_pages):
page = pdf_reader.getPage(i).rotateCounterClockwise(90)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
for i in range(no_of_pages,total_pages):
page = pdf_reader.getPage(i)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
"""
f=FileWriter("rotate_pages.pdf","wb")
pdf_writer = PdfWriter(f)
pdf_writer.write()
"""
if __name__ == '__main__':
path = 'F:\pdf\ex1.pdf'
rotate_pages(path,no_of_pages=10,clockwise=True)
| true
|
e340d8b94dc7c2f32e6591d847d8778ed5b5378b
|
liorkesten/Data-Structures-and-Algorithms
|
/Algorithms/Arrays_Algorithms/isArithmeticProgression.py
| 666
| 4.3125
| 4
|
def is_arithmetic_progression(lst):
"""
Check if there is a 3 numbers that are arithmetic_progression.
for example - [9,4,1,2] return False because there is not a sequence.
[4,2,7,1] return True because there is 1,4,7 are sequence.
:param lst: lst of diff integers
:return: True or False if there is a 3 sequence in the lst.
"""
set_of_values = set(lst)
# Check if there is 3 monotony
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
third_num = abs(lst[i] - lst[j]) + max(lst[i], lst[j])
if third_num in set_of_values:
return True
return False
| true
|
6101f3df70700db06073fd8e3723dba00a02e9d9
|
liorkesten/Data-Structures-and-Algorithms
|
/Algorithms/Arrays_Algorithms/BinarySearch.py
| 577
| 4.21875
| 4
|
def binary_search_array(lst, x):
"""
Get a sorted list in search if x is in the array - return true or false.
Time Complexity O(log(n))
:param lst: Sorted lst
:param x: item to find
:return: True or False if x is in the array
"""
if not lst:
return False
if len(lst) == 1:
return x == lst[0]
mid = len(lst) // 2
if lst[mid] == x:
return True
elif lst[mid] < x:
return binary_search_array(lst[mid + 1:], x)
elif lst[mid] > x:
return binary_search_array(lst[:mid], x)
| true
|
a0e52ed563d1f26e274ef1aece01794cce581323
|
samanthaWest/Python_Scripts
|
/DataStructsAndAlgorithms/TwoPointersTechnique.py
| 784
| 4.3125
| 4
|
# Two Pointers
# https://www.geeksforgeeks.org/two-pointers-technique/
# Used for searching for pairs in a sorted array
# We take two pointers one representing the first element and the other representing the last element
# we add the values kept at both pointers, if their sum is smaller then target we shift left pointer to the
# right. If sum is larger then target we shift right pointer to the left till be get closer to the sum.
def isPairSum(arr, lenghtArray, target):
l = 0 # first pointer
r = lenghtArray - 1 # second pointer
while l < r:
curSum = numbers[l] + numbers[r]
if curSum > target:
r -= 1
elif curSum < target:
l += 1
else:
return [l + 1, r + 1]
| true
|
9a02e277ab565469ef0d3b768b7c9a0c053c2545
|
JamesRoth/Precalc-Programming-Project
|
/randomMulti.py
| 554
| 4.125
| 4
|
#James Roth
#1/31/19
#randomMulti.py - random multiplication problems
from random import randint
correctAns = 0
while correctAns < 5: #loop until 5 correct answers are guessed
#RNG
num1 = randint(1,10)
num2 = randint(1,10)
#correct answer
ans = num1*num2
#asking the user to give the answer to the multiplication problem
guess = int(input("What is "+str(num1)+"*"+str(num2)+"? "))
#did they get it right?
if guess == ans:
correctAns+=1
else:
print("Incorrect! The correct answer is: "+str(ans))
| true
|
ddda27bf9906caf8916deb667639c8e4d052a05f
|
AXDOOMER/Bash-Utilities
|
/Other/Python/parse_between.py
| 918
| 4.125
| 4
|
#!/usr/bin/env python
# Copyright (c) Alexandre-Xavier Labonte-Lamoureux, 2017
import sys
import numbers
# Parser
def parse(textfile):
myfile = open(textfile, "r")
datastring = myfile.read()
first_delimiter = '\"'
second_delimiter = '\"'
index = 0
while(index < len(datastring)):
first = datastring.find(first_delimiter, index, len(datastring))
if (first == -1):
break;
second = datastring.find(second_delimiter, first + len(first_delimiter), len(datastring))
if (second == -1):
break;
index = second + len(second_delimiter);
foundstring = datastring[first + len(first_delimiter):second]
if (len(foundstring) > 0 and not foundstring.isdigit()):
print(foundstring)
quit()
def main():
if len(sys.argv) < 2:
print("No enough arguments. How to use:")
print("parse_between.py [FILE]")
quit()
textfile = sys.argv[1]
# Parsing function
parse(textfile)
# Do stuff
if __name__ == "__main__":
main()
| true
|
49c33bb519c6142f0832435d2a66054baceadf1a
|
cmedinadeveloper/udacity-data-structures-algorithms-project1-unscramble
|
/Task1.py
| 666
| 4.25
| 4
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
phone_nums = []
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
for text in list(reader):
phone_nums.extend(text[:2])
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
for call in list(reader):
phone_nums.extend(call[:2])
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
phone_nums = list(set(phone_nums))
print(("There are {} different telephone numbers in the records.").format(len(phone_nums)))
| true
|
f150c2160c0c5b910fde7e3a05c40fc26e3c213c
|
HopeFreeTechnologies/pythonbasics
|
/variables.py
| 1,419
| 4.125
| 4
|
#So this file has some examples of variables, how they work, and more than just one output (like hi there.py did).
#######################
#
#Below is a variable by the name vname. V for variable and name for, well name.
# Its my first ever variable in Python so by default it's awesome, so i let it know by giving it the value (in the form of a string) awesome lol
#. Note as well that to assign a string to a variable it must still be notated as such eith quotations ^^;
#
#######################
vname = "awesome"
print(vname)
#######################
#
#Variables also have the nifty feature of being capable of changing their assigned value whenever the need arises.
#One of the simplest ways of accomplishing this task is to simply redefine aforementioned value later on inside the same file.
#Like, literally. It can even be immediately following the first value being assigned to it haha
#
#######################
vname = "having all the fun!"
print(vname)
#######################
#
#When the file is compiled (now that the block above has been added) you can see that vname isnt awesome but having all the fun by the second line of output!
#Of course vname can always be awesome again; although you'll have to give it a hand here by running the file a second (or more) time(s) lol
#At their base this is how variables are used. In their simplest format anyways ♡
#
#######################
#~ Hope Currey
| true
|
11f7f93b4690191cd336a3884aa99ca24b5cdd8d
|
phoebeweimh/xiao-g
|
/归并排序.py
| 1,225
| 4.4375
| 4
|
#!/usr/bin/env python
# !coding:utf-8
# 归并排序(英语:Merge sort,或mergesort),是创建在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。
#分治法:
# 分割:递归地把当前序列平均分割成两半。
# 集成:在保持元素顺序的同时将上一步得到的子序列集成到一起(归并)。
import random
def SortByMerge(arr,size):
if size <= 1:
return arr
i = int(size/2)
left = SortByMerge(arr[:i], i)
right = SortByMerge(arr[i:], size - i)
return MergeSort(left, right)
def MergeSort(left, right):
# 比较传过来的两个序列left,right,返回一个排好的序列
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:] # 这时候i或者j到了序列的最后
result += right[j:]
return result
list1=random.sample(range(20),20) #生成无序list
print('waiting sort list:',list1[:])
print('sort ok list:',SortByMerge(list1,len(list1)))
| false
|
d22a954c0a50eb89bd5c24f37cf69a53462e1d0c
|
dinabseiso/HW01
|
/HW01_ex02_03.py
| 1,588
| 4.1875
| 4
|
# HW01_ex02_03
# NOTE: You do not run this script.
# #
# Practice using the Python interpreter as a calculator:
# 1. The volume of a sphere with radius r is 4/3 pi r^3.
# What is the volume of a sphere with radius 5? (Hint: 392.7 is wrong!)
# volume: 523.3
r = 5
pi = 3.14
volume = (4 * pi * r**3) / 3
print(volume)
# 2. Suppose the cover price of a book is $24.95, but bookstores get a
# 40% discount. Shipping costs $3 for the first copy and 75 cents for
# each additional copy. What is the total wholesale cost for 60 copies?
# total wholesale cost: 945.45
discountedPrice = 24.95 * 0.60
firstShippingCost = 3
additionalShippingCost = 0.75
n = 60
firstCopyPrice = discountedPrice + firstShippingCost
additionalCopyPrice = (additionalShippingCost + discountedPrice) * (n-1)
wholesaleCost = firstCopyPrice + additionalCopyPrice
print(wholesaleCost)
# 3. If I leave my house at 6:52 am and run 1 mile at an easy pace
# (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy
# pace again, what time do I get home for breakfast?
# time:
startHour = 6
startHourToSeconds = startHour * 3600.0
startMinutes = 52.0
startMinutesToSeconds = startMinutes * 60
convertToOneHundred = 100.0 / 60
startTime = ( startHourToSeconds + startMinutesToSeconds ) * convertToOneHundred
print(startTime)
beginningRun = 1 * (8 + (15/60) ) * 60
middleRun = 3 * (7+(12/60)) * 60
endRun = 1 * (8 + (15/60)) * 60
totalRunTime = (beginningRun + middleRun + endRun )
breakfast = (( startTime + totalRunTime ) / 3600.0) * (60/100.0)
breakfast = round(breakfast, 2)
print(breakfast)
| true
|
b3c9b758ea0b683aa4762a1e8e30bfffb2074a00
|
spsree4u/MySolvings
|
/trees_and_graphs/mirror_binary_tree.py
| 877
| 4.21875
| 4
|
"""
Find mirror tree of a binary tree
"""
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def mirror(root):
if not root:
return
mirror(root.left)
mirror(root.right)
temp = root.left
root.left = root.right
root.right = temp
def in_order(root):
if not root:
return
in_order(root.left)
print(root.data)
in_order(root.right)
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
""" Print inorder traversal of
the input tree """
print("Inorder traversal of the",
"constructed tree is")
in_order(root1)
""" Convert tree to its mirror """
mirror(root1)
""" Print inorder traversal of
the mirror tree """
print("\nInorder traversal of",
"the mirror treeis ")
in_order(root1)
| true
|
f29923bcb48d0f6fd0ea61207249f57ca0a69c6a
|
spsree4u/MySolvings
|
/trees_and_graphs/post_order_from_pre_and_in.py
| 1,526
| 4.21875
| 4
|
# To get post order traversal of a binary tree from given
# pre and in-order traversals
# Recursive function which traverse through pre-order values based
# on the in-order index values for root, left and right sub-trees
# Explanation in https://www.youtube.com/watch?v=wGmJatvjANY&t=301s
def print_post_order(start, end, p_order, p_index, i_index_map):
# base case
if start > end:
return p_index
# get value for current p_index for updating p_index value
val = p_order[p_index]
p_index += 1
# Print value if retrieved value is of a leaf as there is no more child
if start == end:
print(val)
return p_index
# If not leaf node, get root node index from in-order map
# corresponding to value to call recursively for sub-trees
i = i_index_map[val]
p_index = print_post_order(start, i-1, p_order, p_index, i_index_map)
p_index = print_post_order(i+1, end, p_order, p_index, i_index_map)
# Print value of root node as subtrees are traversed
print(val)
return p_index
def get_post_order(in_order, pre_order):
in_order_index_map = {}
tree_size = len(in_order)
# dictionary to store the indices of in-order travel sequence
# O(n) time and O(n) space is required for the hash map
for n in range(tree_size):
in_order_index_map[in_order[n]] = n
pre_index = 0
print_post_order(0, tree_size-1, pre_order, pre_index, in_order_index_map)
get_post_order([4, 2, 1, 7, 5, 8, 3, 6], [1, 2, 4, 3, 5, 7, 8, 6])
| true
|
965e5afce19c0ab3dcaf484bdafa554dd4d51e4d
|
spsree4u/MySolvings
|
/trees_and_graphs/super_balanced_binary_tree.py
| 2,240
| 4.125
| 4
|
"""
Write a function to see if a binary tree is "super-balanced".
A tree is "super-balanced" if the difference between the depths of any two
leaf nodes is no greater than one.
Complexity
O(n) time and O(n) space.
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_left(self, value):
self.left(Node(value))
return self.left
def add_right(self, value):
self.right(Node(value))
return self.right
def is_super_balanced(root):
if not root:
return True
depths = list()
visited = list()
visited.append((root, 0))
while len(visited):
node, depth = visited.pop()
# If leaf
if (not node.left) and (not node.right):
# If already visited depth
if depth not in depths:
depths.append(depth)
# Two ways we might now have an unbalanced tree:
# 1) more than 2 different leaf depths
# 2) 2 leaf depths that are more than 1 apart
if (len(depths) > 2) or \
(len(depths) == 2 and abs(depths[0]-depths[1]) > 2):
return False
else:
if node.left:
visited.append((node.left, depth+1))
if node.right:
visited.append((node.right, depth+1))
return True
def is_balanced(root):
# Time O(n), Space O(1)
if not root:
return 0
return 1 + abs(is_balanced(root.left) - is_balanced(root.right))
# Balanced tree
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root1.right.left = Node(6)
# root1.right.right = Node(8)
root1.left.left.left = Node(7)
print("SuperBalanced") if is_super_balanced(root1) else print("Unbalanced")
print("Balanced") if is_balanced(root1) == 1 else print("Unbalanced")
# Unbalanced tree
root2 = Node(1)
root2.left = Node(2)
root2.right = Node(3)
root2.left.left = Node(4)
root2.left.right = Node(5)
root2.left.left.left = Node(8)
print("SuperBalanced") if is_super_balanced(root2) else print("Unbalanced")
print("Balanced") if is_balanced(root2) == 1 else print("Unbalanced")
| true
|
3e92fa31734cdd480a102553fda5134de7aed2ba
|
aryansamuel/Python_programs
|
/jumble.py
| 819
| 4.375
| 4
|
# Aryan Samuel
# arsamuel@ucsc.edu
# prgramming assignment 6
# The following program asks the user for a jumbled word,
# then unjumbles and prints it.
# Note: The unjumbled word should be in the dictionary that is read by the prog.
def main(file):
file = open(file,'r')
word_list = file.read().split()
real_word = []
wordx = input('Please enter a jumbled word: ')
word_l = wordx.lower()
for word in word_list:
if sorted(word) == sorted(word_l):
real_word.append(word)
if len(real_word) < 1:
print('Your word cannot be unjumbled.')
if len(real_word) == 1:
print('Your word is %s.' %real_word[0])
if len(real_word) > 1:
print('Your words are: ')
for i in range(len(real_word)):
print(real_word[i])
main()
| true
|
203e35f62d3a64a25c87b1f88f8ba9b7ad33c112
|
Shobhits7/Programming-Basics
|
/Python/factorial.py
| 411
| 4.34375
| 4
|
print("Note that facotrial are of only +ve integers including zero\n")
#function of facorial
def factorial_of(number):
mul=1
for i in range(1,num+1):
mul=mul*i
return mul
#take input of the number
num=int(input("Enter the number you want the fatcorial of:"))
#executing the function
if num<0 :
print("Not possible")
else:
print("Factorial of ",num," is ",factorial_of(num))
| true
|
e98f42af716c60f62e9929ed5fa9660b3a1d678a
|
Shobhits7/Programming-Basics
|
/Python/palindrome.py
| 364
| 4.46875
| 4
|
# First we take an input which is assigned to the variable "text"
# Then we use the python string slice method to reverse the string
# When both the strings are compared and an appropriate output is made
text=input("Enter the string to be checked: ")
palindrom_text= text[::-1]
if text==palindrom_text:
print("Palindrome")
else:
print("Not Palindrome")
| true
|
1b2ec70312c8bf5d022cf2832fb3dfbf93c0d0f2
|
Shobhits7/Programming-Basics
|
/Python/fibonacci_series.py
| 1,110
| 4.40625
| 4
|
# given a variable n (user input), the program
# prints fibinacci series upto n-numbers
def fibonacci(n):
"""A simple function to print fibonacci sequence of n-numbers"""
# check if n is correct
# we can only allow n >=1 and n as an integer number
try:
n = int(n)
except ValueError:
raise TypeError("fibonacci series is only available for n-digits, where n is an integer, and n >= 1")
if n < 1:
raise ValueError("fibonacci series is only available for n-digits, where n is an integer, and n >= 1")
# when we are assured that the value of n is correct,
# we can find the fibonacci sequence
# and finally return it as a string seperated by space
if n == 1:
series = [0]
elif n == 2:
series = [0, 1]
else:
series = [0, 1]
for _ in range(n - 2):
series.append(sum(series[-2:]))
return " ".join(map(str, series))
if __name__ == "__main__":
n = input("Enter the Number of Elements of Fibonacci Series (n >= 1, and type(n) = int): ")
print(fibonacci(n))
| true
|
537bfed643c059426bc9303f369efb0e1a9cc687
|
MS642/python_practice
|
/objects/objects.py
| 1,445
| 4.28125
| 4
|
class Line:
"""
Problem 1 Fill in the Line
class methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
# EXAMPLE OUTPUT
coordinate1 = (3, 2)
coordinate2 = (8, 10)
li = Line(coordinate1, coordinate2)
li.distance()
9.433981132056603
li.slope()
1.6
"""
def __init__(self, point_1, point_2):
self.point_1 = point_1
self.point_2 = point_2
def distance(self):
x1, y1 = self.point_1
x2, y2 = self.point_2
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
def slope(self):
x1, y1 = self.point_1
x2, y2 = self.point_2
return (y2 - y1) / (x2 - x1)
coord_1 = (3, 2)
coord_2 = (8, 10)
li = Line(coord_1, coord_2)
assert li.distance() == 9.433981132056603
assert li.slope() == 1.6
class Cylinder:
"""
Problem 2
# EXAMPLE OUTPUT
c = Cylinder(2,3)
c.volume()
56.52
c.surface_area()
94.2
"""
pi = 3.14
def __init__(self, height=1, radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.pi * self.height * self.radius**2
def surface_area(self):
return 2 * self.pi * self.radius * self.height + 2 * self.pi * self.radius**2
c = Cylinder(2, 3)
assert c.volume() == 56.52
assert c.surface_area() == 94.2
| true
|
22202840ae1c77f10c7e1f301ec5c0262b92e4e3
|
lucasflosi/Assignment2
|
/nimm.py
| 2,011
| 4.40625
| 4
|
"""
File: nimm.py
-------------------------
Nimm is a 2 player game where a player can remove either 1 or 2 stones. The player who removes the
last stone loses the game!
"""
STONES_IN_GAME = 20 #starting quantity for stones
def main():
stones_left = STONES_IN_GAME
player_turn = 1
while stones_left > 0:
if stones_left != STONES_IN_GAME:
print("") #prints a blank on turns after the first turn
print("There are " + str(stones_left) + " stones left")
stones_removed = int(input("Player " + str(player_turn) +" would you like to remove 1 or 2 stones? "))
while input_is_invalid(stones_removed) == False:
stones_removed = int(input("Please enter 1 or 2: "))
while taking_more_stones_than_exists(stones_left,stones_removed) == True:
print("There is only 1 stone left. You cannot remove 2 stones")
stones_removed = int(input("Player " + str(player_turn) +" would you like to remove 1 or 2 stones? "))
stones_left -= stones_removed
player_turn = switch_player(player_turn)
print("")
print("Player " + str(player_turn) + " wins!")
def input_is_invalid(user_turn):
if user_turn == 1 or user_turn == 2:
return True
else:
return False
def taking_more_stones_than_exists(num_stones_left,stones_user_wants_to_remove):
if num_stones_left < stones_user_wants_to_remove:
return True
else:
return False
def switch_player(player_turn):
if player_turn == 1:
new_player_turn = 2
if player_turn == 2:
new_player_turn = 1
return new_player_turn
"""
You should write your code for this program in this function.
Make sure to delete the 'pass' line before starting to write
your own code. You should also delete this comment and replace
it with a better, more descriptive one.
"""
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true
|
f257c04116334c1a701cc28aa5b6b15485eea10a
|
Israel1Nicolau/Python
|
/condAninhadas000.py
| 356
| 4.25
| 4
|
nome = str(input('Digite seu nome: ')).strip().capitalize()
if nome == 'Israel':
print('Que nome bonito!')
elif nome == 'Pedro' or nome == 'Maria' or nome == 'Paulo':
print('Nome bastante comum')
elif nome in 'Ana Juliana Elisabeth Joana':
print('Belo nome feminino')
'''else:
print('Nome normal!')'''
print('Prazer em te conhecer {}'.format(nome))
| false
|
8a99a85a0cb95bb61619ccdb7ed022b29c36aef1
|
jizwang/pythonOOP
|
/OOP/魔法函数.py
| 1,197
| 4.125
| 4
|
# # __call__举例
# class A():
# # def __init__(self):
# # print("哈哈")
# def __call__(self):#对象当函数使用的时候触发
# print("我被调用了")
# # def __str__(self):#当对象被当做字符串使用的时候可以触发这个函数
# # return "图灵学院"
# def __repr__(self):
# return "图灵"
# a = A()
# a
# # print(a)
#__getattr__
# class A():
# name = "NoName"
# age = 18
# def __getattr__(self,name):
# print("没找到啊")
# print(name)
#
# a = A()
# print(a.name)
# print(a.addr)
# #setattr案例
# class Person():
# def __init__(self):
# pass
# def __setattr__(self, name, value):
# print("设置属性:{0}".format(name))
# # self.name = value
# super().__setattr__(name,value)
# p = Person()
# print(p.__dict__)
# p.age = 18
#__gt__
class Student():
def __init__(self,name):
self._name = name
def __str__(self):
return self._name
def __gt__(self, obj):
print("哈哈哈,{0}会大于{1}吗".format(self,obj))
return self._name>obj._name
stu1 = Student("one")
stu2 = Student("two")
print(stu1>stu2)
| false
|
99dae88c68d64b67d1f29de82469af41bec6c687
|
Mauc1201/Python
|
/data_structures/4_funciones_listas2.py
| 604
| 4.28125
| 4
|
# -*- coding: utf-8 -*-
# ------------- Funciones en listas -------------
lista_alfa = [0, 1, 10, 15, [3, 4, 10, 20, 5]]
# Uso de index en listas
print (lista_alfa.index(15))
print (lista_alfa[4].index(20))
#print (lista_alfa[3].index(1)) #Error por indice
if 15 in lista_alfa:
print ("Find")
else:
print ("Not Find")
# Uso de in en listas
print ("IN")
print (2 in lista_alfa)
print (1 in lista_alfa)
print (100 in lista_alfa[4])
print ("NOT IN")
#Uso de not in en listas
print (2 not in lista_alfa)
print (3 not in lista_alfa)
print (3 not in lista_alfa[4])
print (not 100 in lista_alfa[4])
| false
|
6a053f7dfbda90bf296646f4c4a45f5075243c84
|
lion963/SoftUni-Python-Fundamentals-
|
/Functions/Calculations.py
| 378
| 4.1875
| 4
|
def simple_calculator(operator, num1, num2):
if operator=='multiply':
return int(num1*num2)
elif operator=='divide':
return int(num1/num2)
elif operator=='add':
return int(num1+num2)
elif operator=='subtract':
return int(num1-num2)
oper=input()
num_1=float(input())
num_2=float(input())
print(simple_calculator(oper,num_1,num_2))
| false
|
e6d7b94ab9ee72d64ee17dee3db7824653bd5c51
|
mgyarmathy/advent-of-code-2015
|
/python/day_12_1.py
| 1,078
| 4.1875
| 4
|
# --- Day 12: JSAbacusFramework.io ---
# Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.
# They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.
# For example:
# [1,2,3] and {"a":2,"b":4} both have a sum of 6.
# [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
# {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
# [] and {} both have a sum of 0.
# You will not encounter any strings containing numbers.
# What is the sum of all numbers in the document?
import sys
import re
def main():
input_file = sys.argv[1]
json_string = open(input_file, 'r').read()
print int(sum_json_numbers_regex(json_string))
def sum_json_numbers_regex(json_string):
return sum(int(num) for num in re.findall('-?\d+', json_string))
if __name__ == '__main__':
main()
| true
|
5937dd8901f02cb79eb422b7d3778353f540c052
|
filfilt/pythonRepository
|
/Part022 Types of Methods.py
| 805
| 4.25
| 4
|
#Types of Methods
#Eg1:Instance Method
'''
class student:
schoolName = "school of techinology"
def __init__(self,fn,ln):
self.fname =fn
self.lname = ln
def getName(self):
self.fname=self.fname+"1st"
print("your full name is "+ self.fname+" "+self.lname)
s1=student("nega","tafere")
s1.getName()
'''''
#Eg2:Class =>to modify only class variable not instance
class student:
schoolName = "school of techinology"
def __init__(self,fn,ln):
self.fname =fn
self.lname = ln
def getName(self):
self.fname=self.fname+"1st"
print("your full name is "+ self.fname+" "+self.lname)
@classmethod
def myClassmethod(cls):
cls.schoolName="Medicine"
s1=student("nega","tafere")
s1.getName()
s1.myClassmethod()
| false
|
040fcf183a0db97e0e341b7a3e9fec2f8adf24eb
|
BlueMonday/advent_2015
|
/5/5.py
| 1,778
| 4.15625
| 4
|
#!/usr/bin/env python3
import re
import sys
VOWELS = frozenset(['a', 'e', 'i', 'o', 'u'])
NICE_STRING_MIN_VOWELS = 3
INVALID_SEQUENCES = frozenset(['ab', 'cd', 'pq', 'xy'])
def nice_string_part_1(string):
"""Determines if ``string`` is a nice string according to the first spec.
Nice strings contain at least ``NICE_STRING_MIN_VOWELS`` vowels, one
character that appears twice in a row, and do not contain any of the
invalid sequences.
"""
vowel_count = 0
duplicate_sequential_character = False
for i in range(len(string)):
if string[i] in VOWELS:
vowel_count += 1
if i < len(string) - 1:
if string[i] == string[i+1]:
duplicate_sequential_character = True
if string[i:i+2] in INVALID_SEQUENCES:
return False
return (duplicate_sequential_character and
vowel_count >= NICE_STRING_MIN_VOWELS)
def nice_string_part_2(string):
"""Determines if ``string`` is a nice string according to the second spec.
Nice strings contain two letters that appears at least twice in the string
without overlapping and at least one letter which repeats with exactly one
letter between them.
"""
return (re.search(r'(\w\w).*\1', string) and
re.search(r'(\w)(?!\1)\w\1', string))
if __name__ == '__main__':
with open(sys.argv[1]) as f:
strings = [line.strip() for line in f.readlines()]
nice_strings_part_1 = 0
nice_strings_part_2 = 0
for string in strings:
print(string)
if nice_string_part_1(string):
nice_strings_part_1 += 1
if nice_string_part_2(string):
nice_strings_part_2 += 1
print(nice_strings_part_1)
print(nice_strings_part_2)
| true
|
10a4575fc55bc35c004b6ca826f7b50b9d269855
|
jackedjin/README.md
|
/investment.py
| 579
| 4.1875
| 4
|
def calculate_apr():
"Calculates the compound interest of an initial investment of $500 for over 65 years"
principal=500
interest_rate=0.03
years=0
while years<65:
"While loop used to repeat the compounding effect of the investment 65 times"
principal=principal*(1+interest_rate)
"compound interest calculation"
print(f'Afer year {years}, the new principal is {principal}')
years+=1
'''counter which automatically adds 1 into integer variable years until
it reaches 65'''
print(f'On the {years}th year, the principal has become {principal}')
calculate_apr()
| true
|
f44cda077b7939465d6add8a9e845b3f72bc03c2
|
NSLeung/Educational-Programs
|
/Python Scripts/python-syntax.py
| 1,166
| 4.21875
| 4
|
# This is how you create a comment in python
# Python equivalent of include statement
import time
# Statements require no semicolon at the end
# You don't specify a datatype for a variable
franklin = "Texas Instruments"
# print statement in python
print (franklin)
# You can reassign a variable any datatype you want
# this will make the variable a decimal
franklin = 1.0
# You can concatnate seperate strings by adding the + symbol between them
# To convert a number to a string use the str function
print ("Printing number " + str(franklin))
# If statements end with colon
if franklin == 1.0:
# Lines under a if statement, loop or function must be indented.
# The indentation mimics what curly brackets are used for in other languages
print("Franklin equals 1.0")
# Syntax for else if. Also includes colon
elif franklin == 2.0:
print("Franklin equals 2.0")
# Syntax for else statement. Also includes colon
else:
print("Unknock value for Franklin")
# Its True and False. TRUE/FALSE or true/false will not work
if True == True:
print ("True is indeed True")
if False == False:
print ("False is indeed False")
| true
|
dc7b6fdbee9d6a43089e7e1bccadd98deb2d7efc
|
Mezz403/Python-Projects
|
/LPTHW/ex16.py
| 592
| 4.25
| 4
|
from sys import argv # Unpack arguments entered by the user
script, filename = argv # unpack entered arguments into script and filename
txt = open(filename) # open the provided filename and assign to txt
print "Here's your file %r: " % filename # display filename to user
print txt.read() # print the contexts of the file to screen
print "Type the filename again:" # ask for the filename again
file_again = raw_input("> ") # save user input to variable
txt_again = open(file_again) # open the file
print txt_again.read() # print contents of file to screen
txt.close()
txt_again.close()
| true
|
0b7f5b3f5e1b5e5d4bd88c37000bbfa0843af2bd
|
rachelsuk/coding-challenges
|
/compress-string.py
| 1,129
| 4.3125
| 4
|
"""Write a function that compresses a string.
Repeated characters should be compressed to one character and the number of
times it repeats:
>>> compress('aabbaabb')
'a2b2a2b2'
If a character appears once, it should not be followed by a number:
>>> compress('abc')
'abc'
The function should handle letters, whitespace, and punctuation:
>>> compress('Hello, world! Cows go moooo...')
'Hel2o, world! Cows go mo4.3'
"""
def compress(string):
"""Return a compressed version of the given string."""
new_str = string[0]
#new_str = "Hel2o"
current = string[0]
#current = "o"
nums = set("0123456789")
for char in string[1:]:
#char = o
if char == current:
if new_str[-1] in nums:
new_str = new_str[:-1] + str(int(new_str[-1]) + 1)
else:
new_str = new_str + "2"
else:
new_str = new_str + char
current = char
return new_str
compress("Hello, world! Cows go moooo...")
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n')
| true
|
f556169bc651d8d4f3dfef3a7a1696bef15e4664
|
liu770807152/LeetCode
|
/021.merge-two-sorted-lists/21.merge-two-sorted-lists.py
| 1,370
| 4.1875
| 4
|
#עСղѧpython
```
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
#ָͷָ
head = dummy = ListNode(-1)
#ΪյʱȽϴССĽĿָ
while l1 and l2:
if l1.val < l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
#ǵһƵʣһȫĿ
if l1:
head.next = l1
if l2:
head.next = l2
return dummy.next
```
```
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
if not l1 or not l2:
return l1 or l2
#ؼ ݹãΪijl.nextһ
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
```
| false
|
744a17e55227470c63ceb499957400bd486113ab
|
oddporson/intro-python-workshop
|
/strings.py
| 721
| 4.1875
| 4
|
# strings are a sequence of symbols in quote
a = 'imagination is more important than knowledge'
# strings can contain any symbols, not jus tletters
b = 'The meaning of life is 42'
# concatenation
b = a + ', but not as important as learning to code'
# functions on string
b = a.capitalize()
b = a.upper()
b = b.lower()
b = a.replace('more', 'less') # replace all instances of 'more' with 'less'
print(b)
# input/output
print(a)
b = input('Enter a number between (0, 10)')
print(a + ' ' + b)
# conversion between strings and numbers
c = int(b) # useful for converting user inputs to numbers
c = float(b)
d = str(c) # useful for combining a number with a string before printing
print('The entered number was ' + d)
| true
|
d761e36ff3db8724b77a83d79537ee72db4e9129
|
shirishavalluri/Python
|
/Objects & Classes.py
| 2,574
| 4.25
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Import the library
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[12]:
class Circle(object):
#Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius;
self.color = color;
# In[13]:
RedCircle = Circle(10, 'red')
# In[14]:
RedCircle
# In[15]:
dir(RedCircle)
# In[16]:
RedCircle.radius
# In[17]:
RedCircle.color
# In[19]:
RedCircle.radius = 1
RedCircle.radius
# In[21]:
RedCircle.add_radius(2)
# In[22]:
print('Radius of object:',RedCircle.radius)
RedCircle.add_radius(2)
print('Radius of object of after applying the method add_radius(2):',RedCircle.radius)
RedCircle.add_radius(5)
print('Radius of object of after applying the method add_radius(5):',RedCircle.radius)
# In[23]:
BlueCircle = Circle(radius=100)
# In[44]:
BlueCircle.drawCircle
# In[45]:
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
# In[63]:
# Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
# In[64]:
RedCircle = Circle(10, 'red')
# In[66]:
RedCircle.drawCircle()
# In[31]:
RedCircle.radius
# In[38]:
class Rectangle(object):
def __init__(self,width=4,height=5,color ='red'):
self.width=width
self.height = height
self.color = color
def drawRectangle(self):
plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height ,fc=self.color))
plt.axis('scaled')
plt.show()
# In[67]:
SkinnyRedRectangle = Rectangle(2,3,'yellow')
# In[40]:
SkinnyRedRectangle.width
# In[41]:
SkinnyRedRectangle.height
# In[42]:
SkinnyRedRectangle.color
# In[68]:
SkinnyRedRectangle.drawRectangle()
# In[ ]:
| true
|
1b39071c2140b24131741542defa41211e78b360
|
marcvifi10/Curso-Python
|
/Python 1/3 - Colecciones/35 - Ejercicio 2 – Operaciones de conjuntos con listas/Ejercicio 2.py
| 391
| 4.1875
| 4
|
# Ejercicio 2
lista1 = [1,2,3,4,5,4,3,2,2,1,5]
lista2 = [4,5,6,7,8,4,5,6,7,7,8]
# Elimine los elementos repetidos de las dos listas
a = set(lista1)
b = set(lista2)
union = list(a | b)
soloA = list(a - b)
soloB = list(b - a)
interseccion = list(a & b)
print(f"Union: {union}")
print(f"Solo elementos A: {soloA}")
print(f"Solo elementos B: {soloB}")
print(f"Intersección: {interseccion}")
| false
|
386525ce0b00e19ab86ef73ec516d298d859e071
|
marcvifi10/Curso-Python
|
/Python 2/1 - Sintaxis Básica/7 - Sintaxis Básica V. Las listas. Vídeo 7.py
| 614
| 4.15625
| 4
|
lista = ["Marc","Alex","Juan"]
print(lista[:])
print(lista[:2])
print(lista[1:2])
print(lista[1:3])
# Añadimos un nuevo valor a la lista
lista.append("Marina")
# Devuelve la posición del valor
print(lista.index("Marc"))
# Muestra si el valor esta dentr de la lista
print("Alex" in lista)
# Añadimos más valores a la lista
lista.extend(["N","J"])
# Eliminamos el valor con el valor "Marc"
print(lista)
lista.remove("Marc")
print(lista)
# Eliminar el último elemento de la lista
lista.pop()
print(lista)
# Juntamos dos listas
lista2 = [1,2,3]
lista3 = [4,5,6]
lista4 = lista2 + lista3
print(lista4)
| false
|
7350e2b6288296a457d3791d5e2cebdc01baace3
|
dkurchigin/gb_algorythm
|
/task7.py
| 1,187
| 4.375
| 4
|
# По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков.
# Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним
a = int(input("Введите длинну первого отрезка\n\n"))
b = int(input("Введите длинну второго отрезка\n\n"))
c = int(input("Введите длинну третьего отрезка\n\n"))
if (a < b + c) or (b < a + c) or (c < a + b):
print("Треугольник существует")
if a == b and b == c:
print("Треугольник равносторонний")
else:
if a == b or b == c or c == a:
print("Треугольник равнобедренный")
else:
print("Треугольник разносторонний")
else:
print("Треугольник не существует")
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.