blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
0b1df9fd6720310eb23193cbdede99bb44dc4435 | 3l-d1abl0/DS-Algo | /py/oops/magic_methods.py | 923 | 4.03125 | 4 | #Many operations are handled by the internal Magic Methods
#Which can used to provide custom functionality in your own classes
class SumList(object):
def __init__(self, this_list):
self.my_list = this_list
def __add__(self, other):
new_list = [x + y for x,y in zip(self.my_list, other.my_list)... |
058b5cd5b029e793d540088841ce77d3510d710b | 3l-d1abl0/DS-Algo | /py/prims_minimul_spanning_tree.py | 2,936 | 3.71875 | 4 | import sys
import heapq
from queue import PriorityQueue
from collections import defaultdict
class Graph(object):
"""Graph"""
def __init__(self, nov, noe, edges, weights):
self.number_of_nodes = nov
self.number_of_edges = noe
self.edges = edges
self.weights = weights
#ad... |
d9cd0df4cf085be74f125a0dd34cb4405caa81fd | 3l-d1abl0/DS-Algo | /py/dfs.py | 1,050 | 3.78125 | 4 | from queue_stack import Queue
class Graph:
def __init__(self):
self.graph = {}
def addEdge(self, a, b):
if a in self.graph:
self.graph[a].append(b)
else:
self.graph[a]=[b]
if b in self.graph:
self.graph[b].append(a)
else:
... |
f42878abfc9c66da2939bb41afa19235150781a2 | 3l-d1abl0/DS-Algo | /py/knapsack_functionla.py | 848 | 3.78125 | 4 |
class Items:
def __init__(self, val, wt):
self.value = val
self.weight = wt
def __str__(self):
return str(self.__class__) + ": " + str(self.__dict__)
def compare(it1, it2):
return (it2.value/it2.weight) - (it1.value/it1.weight)
def fractional_knapsack(W, Itm):
'''
... |
3e19b68db20afb1391f15588b5b559546479eb76 | 3l-d1abl0/DS-Algo | /py/Design Patterns/Structural Pattern/decorator.py | 1,356 | 4.25 | 4 | '''
Decorator Pattern helps us in adding New features to an existing Object Dynamically,
without Subclassing.
The idea behind Decorator Patter is to Attach additional responsibilities to an object Dynamically.
Decorator provide a flexible alternative to subclassing for extending Functionality.
'''
class WindowInterf... |
12ef15a6246b2566d6c6b235a5d42cf2f291f46a | 3l-d1abl0/DS-Algo | /py/word-ladder-bidirectional.py | 1,875 | 3.703125 | 4 | class Node():
def __init__(self, name, distance):
self.word = name
self.len = distance
def differByOne(a, b):
if len(a) != len(b):
return False
counter = 0
for i in range( len(a) ):
if a[i]!=b[i]:
counter +=1
return True if counter ==1 else False
def ... |
732445f24a46b56c680fe2c877946a1de3867db8 | 3l-d1abl0/DS-Algo | /py/lis_nlogn.py | 716 | 3.5 | 4 | def bi_search(arr,num):
ft = 0
lt = len(arr)-1
while(ft+1<lt):
#print ft,lt,"x"
mid = (ft+lt)/2
if num < arr[mid]:
lt = mid
elif num > arr[mid]:
ft = mid
else:
return mid
return lt
def lis(num):
lt = len(nu... |
cad40748c2252e9b6456df89a9cea828afdcb381 | 3l-d1abl0/DS-Algo | /py/trie.py | 4,266 | 3.765625 | 4 | class Node:
def __init__(self):
self.children = [None] *26
self.isLeaf = False
def isLeafNode(self):
return self.isLeaf is True
def ifFreeNode(self):
for i in self.children:
if i:
return False
return True
class Trie:
d... |
b2625733d1747bbc717ac7295aef5e00d27e217d | 3l-d1abl0/DS-Algo | /py/queue_stack.py | 1,571 | 3.953125 | 4 | class Stack:
def __init__(self):
self.stack = []
def empty(self):
if self.stack.__len__() <1:
return True
else:
return False
def pop(self):
if len(self.stack) < 1:
return None
return self.stack.pop()
def push(self, item):
... |
9095b300ff6e988c6e432f62850e8155e9262299 | 3l-d1abl0/DS-Algo | /py/testing/pytest/assert-and-exceptions/test_assert.py | 1,558 | 3.84375 | 4 | '''
Pytest allows the use of the built in python assert statement for performing verifications in a unit test.
- The normal comparison operators can be used on all python data types: less than, greater than, less than or equal, greater than or equal, equal, or not equal
- Pytest expands on the messages that are reporte... |
bb48d661adb07245a5b587203f15af9c17c9e88e | 3l-d1abl0/DS-Algo | /py/substring_slicing.py | 552 | 3.671875 | 4 | def isPalindrome(str):
# Run loop from 0 to len/2
print str
for i in xrange(0, len(str)/2):
if str[i] != str[len(str)-i-1]:
return False
#print 'returning True'
return True
N= int(raw_input())
for i in xrange(N):
str = raw_input()
str_len = len(str)
flag = False
... |
9c86c1984a628b5d6a0f9d6d1bdf70903336adf8 | dhruvmehtadm/K-Means-Clustering | /Iris_kmeans.py | 2,152 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#importing the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# In[5]:
#importing the dataset with pandas
dataset = pd.read_csv('Iris.csv')
# In[6]:
dataset
# In[10]:
X = dataset.iloc[:,[1,2,3,4]].values
# In[11]:
X
# ... |
d22bf8ab461eb1269afc319bd0296b11cdb3b9e1 | guillaumerosinosky/Segmentation | /minimalexample.py | 659 | 3.65625 | 4 | #!/usr/bin/env python
import segment
# Create some data
data = segment.DataContainer([0, 1, 2, 3, 4], [0, 1, 2, 1, 0])
# Create a segmenter instance which fill fit 2 straight lines
segmenter = segment.TopDown(segment.LinearRegression, 2)
# do the fitting
fits = segmenter.segment(data)
# extract the two lines
line1... |
c6ce174dd78a130dbbd716d2f563e36db4585d59 | sersavn/practice-hackerrank | /Python/Collections/CollDeque.py | 759 | 3.921875 | 4 | #Task
#Perform append, pop, popleft and appendleft methods on an empty deque d.
#Input Format
#The first line contains an integer N, the number of operations.
#The next N lines contains the space separated names of methods and their values.
#Output Format
#Print the space separated elements of deque d.
#Sample Input... |
1fc9becc3e5f89370b225e42fcddb4cbd455d7b2 | sersavn/practice-hackerrank | /Python/ErrorsAndExceptions/Exceptions.py | 623 | 3.96875 | 4 | #Task
#You are given two values a and b.
#Perform integer division and print a/b.
#Input Format
#The first line contains T, the number of test cases.
#The next T lines each contain the space separated values of a and b.
#Output Format
#Print the value of a/b.
#In the case of ZeroDivisionError or
#ValueError, print th... |
8d70926520d5584eef944f534db713e54777fb20 | sersavn/practice-hackerrank | /Python/Itertools/Maximizeit.py | 802 | 3.5625 | 4 |
#Sample Input
#3 1000
#2 5 4
#3 7 8 9
#5 5 7 8 9 10
#
#Sample Output
#206
import itertools
answer = int()
listone = list()
element2 = list()
def square(list):
return [i ** 2 for i in list]
K, M = map(int,input().split())
for randomvalue in range(K):
element = list(sorted(map(int,input().split()))[:1])
... |
f01a757ecd4044cd09353abba40df7eecec36b4b | sersavn/practice-hackerrank | /Python/Basic_data_types/Find2ndLrgstNum.py | 454 | 3.703125 | 4 | #You are given n numbers. Store them in a list and find the second largest number.
#The first line contains n. The second line contains an array A[] of n integers each separated by a space.
#sample imput
#5
#2 3 6 6 5
#sample output
#5
n = int(input())
arr = map(int, input().split())
arr = list(arr)
print(arr, type... |
b0473f985e7aa77cd8466d97db13bcda2900e7bf | sersavn/practice-hackerrank | /Python/ErrorsAndExceptions/IncorrectRegex.py | 392 | 3.625 | 4 | #Sample Input
#2
#.*\+
#.*+
#Sample Output
#True
#False
#Explanation
#.*\+ : Valid regex.
#.*+: Has the error multiple repeat. Hence, it is invalid.
import re
sampl = 'Aa3 fF8s'
for i in range(int(input())):
reg = input()
try:
check = re.findall(reg, sampl)
print('True')
except:
... |
76628ce73e678e11c8d25f3eda635a56a1ac30e5 | sersavn/practice-hackerrank | /Python/Sets/setadd.py | 230 | 3.921875 | 4 | #Sample Input
#7
#UK
#China
#USA
#France
#New Zealand
#UK
#France
#Sample Output
#5
s = set()
for countries in range(int(input())):
country = str(input())
print(country, type(country))
s.add(country)
print(len(s))
|
67344db92b82fe7664ac5ea9121204527880a7a8 | pnadolny13/python_practice_scripts | /Char Input.py | 257 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 26 20:57:57 2016
@author: pnadolny
"""
name = input("What is your name? ")
print ("Hi " + name)
age = int(input("What is your age? "))
print ("You will be 100 years old in " + str(2116-age)) |
28c8c27bec271e04d446938bbc4f2b27ec90d429 | Existentio/phoenix_story | /core/data/StopWordsManager.py | 1,692 | 3.53125 | 4 | import os
class StopWordsManager:
"""Extracts specific word lists for main processing."""
def get_redundant_words(self, lang):
redundant_words = []
if lang == 'ru':
abs_path = os.path.abspath("data/stop_words/redundant/russian")
dir_path = open(abs_path, 'r', encoding=... |
dd08e309662b9176b64bfc1e30dd9fa7364ba352 | KevinRNelson/TwitterFollowerBot | /notification.py | 1,716 | 3.671875 | 4 | from abc import ABC, abstractmethod
from message import *
import os
class Notification(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def notify(self, followed_accounts: dict, unfollowed_accounts: dict) -> None:
pass
class CompositeNotification(Notification):
de... |
a9c3eaf87fb86da5486d03a66ca702d6d27f083e | Nikoleta-v3/rsd | /assets/code/src/find_primes.py | 697 | 4.3125 | 4 | import is_prime
import repeat_divide
def obtain_prime_factorisation(N):
"""
Return the prime factorisation of a number.
Inputs:
- N: integer
Outputs:
- a list of prime factors
- a list of the exponents of the prime factors
"""
factors = []
potential_factor = 1
... |
3b51de92d1c627af2da53c6f0f49feffb2255dc9 | Deba1998/coding | /python/strngmanu.py | 329 | 3.53125 | 4 | t=int(input())
for i in range(t):
s=input()
dp=[0]*len(s)
for i in range(len(s)):
if s[i].isdigit()==False:
dp[i]=1
print(dp)
if dp.count(0)==len(dp):
print("Valid Format")
elif dp.count(1)==len(dp):
print("Its a String")
else:
print("Its an AlphaN... |
259767d60d5f50d1756015065103b08019b7c6fe | Deba1998/coding | /infytq python programs/infytq4.py | 286 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 11:28:13 2020
@author: DELL
"""
s=input()
t=[]
for i in range(len(s)):
if s[i]!='@' and s[i]!='#':
t.append(s[i])
t.reverse()
for i in range(len(s)):
if s[i]=="@" or s[i]=="#":
t.insert(i,s[i])
print("".join(t)) |
7dc5f27bf0aaec5b39a55bc538c95703bee25c12 | Deba1998/coding | /infytq python programs/infytq3.py | 779 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 10:50:49 2020
@author: DELL
"""
s=input()
count=0
sta=[]
for i in range(len(s)):
if s[i]=="(" or s[i]=="{" or s[i]=="[":
sta.append(s[i])
else:
if len(sta)==0:
print(i+1)
count+=1
break
else:
... |
99a2fd4ee33a4f7258a982ef0d171a7fadb42505 | Deba1998/coding | /python/dp4.py | 301 | 3.515625 | 4 | s=input()
if len(s)==1:
print(s)
else:
l=[]
for i in s:
l.append(i)
if l[1]==l[0]:
if l[0]=="z":
l[1]=="a"
else:
l[1]=chr(ord(l[0])+1)
for i in range(2,len(s)):
if l[i]==l[i-1]:
l[i]=l[i-2]
print("".join(l)) |
24541c46b655fb7a95ee00105f97c1bba0ffcf6a | AntonioIatonna/ICS4U1-Software-Assignment | /Lottery Program/lottery_final_v2.py | 4,895 | 3.65625 | 4 | from tkinter import *
import time
import random
tickets = []
cpuTicket = []
matches = []
printTickets = []
printResults = []
tFrames = []
rFrames = []
# Begin Code
# Get user ticket quantity
print("Welcome to Lotto 6/49!\nPlease choose how many tickets you would like to play...")
while True:
try:
... |
c0b18e90727a0d6741d459c3c58d10efee69bbaf | oorepenworkoo/arcade | /models.py | 1,358 | 3.546875 | 4 | import arcade.key
class World:
def __init__(self, width, height):
self.width = width
self.height = height
self.ship = Ship(self,width/2,height/6)
def update(self, delta):
self.ship.update(delta)
def on_key_press(self, key, key_modifiers):
if key == arcade.key.UP:
... |
eab918b7c35fd564dfc54f15d0d2b43b65bf9a46 | devkant/learning-Python | /mindstorm.py | 671 | 3.75 | 4 | import turtle
def draw_square(someturtle):
for i in range(0,4):
someturtle.forward(100)
someturtle.right(90)
def draw_circle(angie):
angie.shape("arrow")
angie.color("blue")
angie.circle(100)
def draw_art():
window = turtle.Screen()
window.bgcolo... |
c446f2b918b80fc1f4f327892e431707749e3c00 | EmonMajumder/All-Code | /Python/tax_calc.py | 1,295 | 4.09375 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Tax_Calculator
"""
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
print("Welcome to Emon's online shop")
totalBil... |
4923d24d114c3ce22708e6f941fe5cc89e660547 | EmonMajumder/All-Code | /Python/Guest_List.py | 1,399 | 4.125 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Data_to_file
"""
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
fileName=input("File Name: ")
accessMode=input("A... |
f32868718d2cfae9a32853eba3c8971f4213a3b4 | EmonMajumder/All-Code | /Python/CoffeeShop.py | 769 | 3.828125 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Coffeeshop
"""
def main():
while True:
try:
originalBill = float(input("What is your original bill amount?: "))
break
e... |
3046212f11a23129f633fc04b2e6411a8636f949 | EmonMajumder/All-Code | /Python/Auto_Insurance.py | 3,013 | 4.1875 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Auto_Insurance
"""
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
#Function that determine the insurance rate if the... |
e1457e85ef66c4807ffcb5446b89813e27644908 | EmonMajumder/All-Code | /Python/Leap_Year.py | 1,319 | 4.4375 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Leap_year
"""
#Pseudocode
# 1. Define name of the function
# 2. Select variable name
# 3. Assign values to 3 variable for input %4, 100 & 400
# 4. determine if inpu... |
29fb6201b823c3b1564250bbb7b50913ea1bc449 | EmonMajumder/All-Code | /Python/RestaurantBill.py | 1,472 | 3.984375 | 4 | <<<<<<< HEAD
#Don't forget to rename this file after copying the template
#for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: Tech Check- 1
"""
def main(): #<-- Don't change this line!
#Write your code below. It must be indented!
originalBill = 85
taxAmount =... |
b673ff8dbcf6f4618937f7e0a9a41038d72baf62 | kimsoosoo0928/BITCAMP_AI_STUDY | /keras2/keras68_1_sigmoid.py | 205 | 3.53125 | 4 | # sigmoid
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
x = np.arange(-5, 5, 0.1)
print(len(x))
y = sigmoid(x)
plt.plot(x,y)
plt.grid()
plt.grid() |
176bafe898098d3da95602acc1b3d95a2816bcd3 | sumitpurandare/My_git_repo | /for_loop.py | 156 | 3.6875 | 4 | for x in range (0,11,2):
print (x)
#range iniial value is starting value,
#where we can go with the range which exclude the given vlue,
#range value
|
1f6dbdf716ac43a3e7c4e008fb17f2e55237f427 | sumitpurandare/My_git_repo | /input.py | 178 | 3.640625 | 4 | #Pythn input
# Complied by :Sumit Purandare
print("Enter your name")
x=input()
print("Enter your age")
y=input()
print ("Hi!",x, "Your age is :",y)
print("How old are you?", end=' ')
|
2b3f30e3cbbe720e1012682e595ec117511b2547 | sumitpurandare/My_git_repo | /Example2.py | 296 | 3.953125 | 4 | #Question 2: Given a range of numbers. Iterate from o^th number
# to the end number and print the sum of the current number
# and previous number
def sumnum(num):
previousnum = 0
for i in range(num):
sum = previousnum + i
print(sum)
previousnum = i
sumnum(10) |
361b36563a6125db09fd7234e05b10de5ac134c8 | sumitpurandare/My_git_repo | /List.py | 668 | 4.03125 | 4 | #list or array formation in Pyhton
#file name: List.py
#complied by : Sumit Purandare
#==================================================#
print("Below is list ")
spam=["cat","Dog","Sheep","Crocodile","Lion","Monkey"]
print("index 0 is ", spam[0])
spam1=[["Black","Red","Orange"],[100,200,300],[1.0,2.0,3.0]]
print(spam1... |
5e54a2bd41db346b7084f7e97faee88d37b168ab | lemon89757/Teaching_manage_system | /entity/lesson.py | 1,158 | 3.578125 | 4 | class Lesson(object):
def __init__(self, lesson_name, teacher_id, limit_number):
self._name = lesson_name
self._teacher_id = teacher_id
self._students = []
self._number_students = 0
self._limit_number = limit_number
@property
def name(self):
return self._name... |
a63b8c366aaff7dec8b94ba0cbcced2e4e95333d | BrandonMosconi/Python-programming-exercises | /Solutions/17.py | 619 | 3.53125 | 4 | class Exercise17Handler():
def __init__(self):
pass
def bankBalance(self):
self.balance = 0
while True:
self.statement = input("> ")
if not self.statement:
break
else:
if self.statement[0] == "D":
... |
eceaef8351c155d0f5338e06a829f12f4adc1fb9 | BrandonMosconi/Python-programming-exercises | /Solutions/13.py | 905 | 3.765625 | 4 | class Exercise13Handler():
def __init__(self,strInp):
self.strInp = strInp
def intstrCount(self):
"""We could import the set of lower-case letters, and define
a set of numbers. Or, we could use the built-in functions
.isdigit() and .isalpha()"""
self.dictCount =... |
20839ec93ad82225c3cf940b1df677fb6c3a8a91 | Nattawut-CS/AI-Lab01 | /introduce_networkx.py | 1,064 | 3.6875 | 4 | import networkx as nx
import matplotlib.pyplot as plt
# create an emtry graph
g = nx.Graph()
# ----------------- adding nodes to graph -----------------
# adding just one node (เพิ่ม 1 โหนด)
g.add_node('a')
# a list of nodes (เพิ่มโหนดแบบเป็นลิสต์, หลายโหนดทีเดียว)
g.add_nodes_from(['b', 'c'])
demoNodes = ['d', 'g']
... |
f5686f26ac19e7b7ef7cd722925d81c5b212099e | Nattawut-CS/AI-Lab01 | /renaming_nodes.py | 413 | 3.609375 | 4 | import networkx as nx
import matplotlib.pyplot as plt
# create
g = nx.path_graph(4)
province ={0:'Bangkok', 1:'Pathumthani', 2:'pattaya', 3:'Ayutthaya'}
# rename nodes
h = nx.relabel_nodes(g, province)
print('nodes of graph : {}' .format(h.nodes))
print(f'edges of graph : {h.edges}')
# with_labels = show label of n... |
87a275e53d8b9d6c10674087c3967af6d2e18c0f | NabilAbdHadi/NLP_Project | /tokenization sentence.py | 3,040 | 3.546875 | 4 | import language_detection as ld
"""from the PreProcess.py:
the output has been exported to "new file2" """
# iniatialize the counter of each language frequency in the file
malay = 0
english = 0
mixed = 0
other = 0
# initialize the array for each category
malaySen = []
englishSen = []
mixedSen = []
otherSen ... |
166cb7d0653281b3cf51693940b265361fcb5bf0 | Mproxima/python1 | /Snake and ladder.py | 949 | 3.8125 | 4 |
# coding: utf-8
# In[9]:
import random
def rolldice():
sum = 0
while(sum!=1):
input("Enter to roll dice ")
sum = random.randrange(1,7)
print ("You got "+str(sum)+"\n")
print ("Ok..you are into the game now \n")
while(sum!=100):
input("enter to roll dice")
... |
580a21a1bf59e67c7c524b10b03579e1bc41b869 | MarcuzHuang/GuessNumber | /GuessNumber.py | 435 | 3.6875 | 4 | #產生一個隨機整數1~100
#讓使用者重複輸入數字去猜
#猜對的話 印出"終於猜對了!"
#猜錯的話 印出"比答案大或小"
import random
r = random.randint(1,100)
while True:
ans = input('請輸入一數字介於1~100 : ')
ans = int(ans)
if ans == r :
print('終於猜對了!')
break
else:
if ans < r :
print('您的數字較答案來的小')
else:
print('您的數字較答案來的大')
|
8e460c4e3941758e290abbb063c7ba3e0a60cc9c | Aaron09/AIEditingTools | /RedEyeRemover/red_eye_remover.py | 2,755 | 3.71875 | 4 | import cv2
import numpy as np
def remove_red_eye(red_eye_image):
"""
Receives an image as input, copies it, and removes the red eye from the image
Returns a new image without red eye
"""
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
face_cascade = cv2.CascadeClassifier('haarcascade... |
06df93f53587e418979404b1ebc750ea888a3ac2 | falcon-ram/PythonTest | /test20_try.py | 301 | 4.03125 | 4 | # Try/except
try:
#value = 10/0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print("Devided by 0")
except ValueError as err:
print(err)
print("Invalid Input")
except: # catches all exceptions
print("Error")
print("Carry on with code!!!") |
a5f4fed0132815a9836d3ae18acd1747e50d972a | falcon-ram/PythonTest | /test12_ifcmp.py | 345 | 4.03125 | 4 | def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(300,4,5))
def is_dog(animal):
if animal == "dog":
print("This is a dog")
else:
print("This is n... |
2b816ecc530802cb378566ca4b743a641e5d0c04 | LarisaOvchinnikova/Python | /1 - Python-2/1 - variables, input, print/MilesToFeet.py | 89 | 3.9375 | 4 | miles = float(input("Enter number of miles: "))
feet = miles * 5280
print("Feet:", feet)
|
71952611efa6c60877e00dcd85c9ee1d540b3a7b | LarisaOvchinnikova/Python | /HW8 + mini bank app/2.- Get the century.py | 634 | 3.84375 | 4 | #Get the century
#Create a function that takes in a year and returns the correct century.
def getCentury(year):
import math
cent = math.ceil(year/100)
cent = str(cent)
print(cent[-1])
if cent[-1] == "1" and cent != '11':
letters = 'st'
elif cent[-1] == "2" and cent != '12':
lette... |
6db5a7c1c9129832dc05019d6eaa8637fd2d834c | LarisaOvchinnikova/Python | /1 - Python-2/11 - dictionaries/6 - Rock, Paper, Scissors.py | 458 | 3.578125 | 4 | # Rock beats Scissors
# Scissors beats Paper
# Paper beats Rock
def rps(player1, player2):
player1 = player1.lower()
player2 = player2.lower()
rules = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
if rules[player1] == player2:
return "The winner is play... |
0182b73ebf8268ed9fd3ecb5fb18fe3feaf0ba84 | LarisaOvchinnikova/Python | /HW11 - lottery and randoms/methods strptime and strftime.py | 1,651 | 4.15625 | 4 | from datetime import datetime, date, timedelta
today = datetime.today()
print(str(today)) # 2020-05-10 20:46:17.842205
print(type(str(today))) # <class 'str'>
# strftime - переводим время из формата datetime в строку
today = today.strftime("%B %d, %Y") # %B - полный месяц, % d - номер дня, %Y год
print(today) # "Ma... |
a595f993f1f05e9bd3552213aca426ca69610ab1 | LarisaOvchinnikova/Python | /HW2/5 - in column.py | 401 | 4.3125 | 4 | # Print firstname, middlename, lastname in column
firstName = input("What is your first name? ")
middleName = input("What is your middle name? ")
lastName = input("What is your last name? ")
m = max(len(firstName), len(lastName), len(middleName))
print(firstName.rjust(m))
print(middleName.rjust(m))
print(lastName.rjus... |
71bf9af30dcf07af07a0a92c1fa88ed6b98faa3f | LarisaOvchinnikova/Python | /arrays/input elements of array.py | 131 | 3.90625 | 4 | a = []
n = int(input('Enter length of a list: '))
for i in range(0, n):
a.append(int(input(f"Enter {i+1} element: ")))
print(a) |
6e07e2678482e47821f7aea432310434af2ac9d7 | LarisaOvchinnikova/Python | /HW16/2 - Password Generator.py | 728 | 3.703125 | 4 | import string
import random
#Воспользуйтесь модулем string чтобы получить разные символы для пароля
s_p = string.punctuation
s_l = string.ascii_letters
s_d = string.digits
easy_str = list(s_l)
med_str = list(s_d + s_l)
strong_str = list(s_d + s_l + s_p)
level = input("Enter level of difficulty for password: 1 - easy, 2... |
c2b369c02980996c33e0254afb608a83284141bb | LarisaOvchinnikova/Python | /1 - Python-2/13 - files/HW13/1a. Read the book and count words.py | 886 | 3.875 | 4 | Не работает еще проверить
import string
file = open("harry potter and the sorcerer's stone.txt", encoding="utf-8-sig")
text = file.read()
text_new = ""
# for char in text:
# if char not in string.punctuation:
# text_new += char
text_new = [char for char in text if char not in string.punctuation]
text = te... |
5a803609ceba7113344e7c50936628feeb91b735 | LarisaOvchinnikova/Python | /1 - Python-2/11 - dictionaries/HW11/Count words in the text222.py | 586 | 3.75 | 4 | # def count_words(text):
# dct = {}
# for word in text.lower().split():
# if word in dct:
# dct[word] += 1
# else:
# dct[word] = 1
# return dct
def count_words(text):
dct = {}
for word in text.lower().split():
dct[word] = dct.get(word, 0) + 1
ret... |
c3091ac5066645b0635d21888990602689f034a1 | LarisaOvchinnikova/Python | /1 - Python-2/7 - Tuples/HW7/1(2) - Sum Fractions.py | 366 | 3.703125 | 4 | def sum_fractions(arr):
return round(sum([el[0] / el[1] for el in arr]))
def sum_fr(arr):
return round(sum([numerator/denominator for numerator, denominator in arr]))
print(sum_fractions([[18, 13], [4, 5]]))
# print(sum_fractions([[36, 4], [22, 60]]))
# print(sum_fractions([[11, 2], [3, 4], [5, 4], [21, 11... |
07d115012a042f1d08bc4a7d9053953fed81466f | LarisaOvchinnikova/Python | /codewars python/strings/Character Counter.py | 191 | 3.765625 | 4 | #https://www.codewars.com/kata/56786a687e9a88d1cf00005d
def validate_word(word):
word = word.lower()
arr = [word.count(el) for el in word]
return all([el == arr[0] for el in arr]) |
748e6339432522cb6be826709f014aee27cf8a18 | LarisaOvchinnikova/Python | /1 - Python-2/7 - Tuples/HW7/1. Use list comprehension to create a list of tuples of first and last letter of the word.py | 148 | 3.75 | 4 | def list_tuples(arr):
return [(el[0], el[-1]) for el in arr]
print(list_tuples(['Apricot', 'Cat', 'Dog', 'Ocelot', 'Zebra', 'Bat', 'Orange'])) |
a8328880ba2b0e3faf71d6a90585214843bb90d5 | LarisaOvchinnikova/Python | /tasks for students/guess number.py | 632 | 4 | 4 | # import random
from random import randint
from datetime import datetime, date, timedelta
#num = random.randint(0,100) # random integer [0-10]
num = randint(1, 100)
print("I know the number from 0 to 100. What number I have?")
answer = int(input("Guess the number: "))
start = datetime.today()
count = 1
while not answe... |
e2b2a0b23cc2271707705eb92870c6a1a5a34d9f | LarisaOvchinnikova/Python | /HW12 (datetime)/2 - Transorm datetime into a string.py | 584 | 4.3125 | 4 | from datetime import datetime
# strftime - переводим время из формата datetime в строку
today = datetime.today()
print(today)
year = today.strftime("%Y")
print(f"year: {year}")
month = today.strftime("%m")
print(f"month: {month}")
day = today.strftime("%d")
print(f"day: {day}")
time = today.strftime("%I:%M:%S") #12-... |
6605e6819ca6490521e37c1e918feb5099342739 | LarisaOvchinnikova/Python | /1 - Python-2/18 - classes/guessing game class.py | 1,246 | 3.96875 | 4 | import random
class GuessNumber:
def __init__(self, min_value, max_value):
self.min_value = min_value
self.max_value = max_value
self.number = random.randint(min_value, max_value)
self.guesses = 0
def get_guess(self):
while True:
guess = input(f"Try to guess... |
97a0e169f4df4ea8a11dd6ff0db8d627d92ffcf4 | LarisaOvchinnikova/Python | /strings/string.py | 1,032 | 4.34375 | 4 | s = "Hi "
print(s * 3)
print('*' * 5)
num = 6
num = str(num)
print(num)
print("Mary\nhas\na\nlittle\nlamb ")
print("I\'m great")
print("I have a \"good\" weight")
print(len("hello"))
name = "Lara"
print(name[0])
print(name[len(name)-1])
print(name.index("a"))
indexOfR = name.index('r')
print(indexOfR)
# Python console:... |
740d9520f451422543ec51d917e273e38edd436c | LarisaOvchinnikova/Python | /1 - Python-2/18 - classes/HW18/1 Create Employees.py | 714 | 3.859375 | 4 | class Employee:
raise_rate = 1.05
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
self.email = f"{first_name}.{last_name}@company.com"
def apply_raise(self):
#self.salary *= Employee.rais... |
77b6d6b9d880e77781161aa29692f29e54dfd16d | LarisaOvchinnikova/Python | /1 - Python-2/6 - List Comprehensions/HW6/5. Filter non-numbers.py | 276 | 3.75 | 4 | def filtered_list(lst):
return [el for el in lst if type(el) == int]
arr1 = [1, False, 2, 'a', 'b', True]
arr2 = [1, 'a', None, 'b', None, 0, 15]
arr3 = [1, 2, True, 'aasf', '1', '123', 123]
print(filtered_list(arr1))
print(filtered_list(arr2))
print(filtered_list(arr3)) |
ef36ed78ceee68ae2d14c1bb4a93605c164c9795 | LarisaOvchinnikova/Python | /1 - Python-2/10 - unit tests/tests for python syntax/variable assignment1.py | 682 | 4.15625 | 4 | # Name of challenger
# Variable assignment
# Create a variable with the name `pos_num` and assign it the value of any integer positive number in the range from 10 to 200, both inclusive.
#Open test
class TestClass(object):
def test_1(self):
"""Type of variable is int"""
assert type(pos_num) == in... |
6c45d63bda300a47a6fdc01baf57bcf8f08e888a | LarisaOvchinnikova/Python | /1 - Python-2/5 - Types of data(lists, tuples...)/HW5/7- Count Palindrome Numbers in a Range.py | 313 | 3.765625 | 4 | def count_palindromes(n, m):
res = []
for i in range(n, m+1):
lst = list(str(i))
reverse = lst[::-1]
if "".join(lst) == "".join(reverse):
res.append(i)
return res
print(count_palindromes(1, 10))
print(count_palindromes(8, 34))
print(count_palindromes(1500, 1552)) |
8b92cf3e62a897fee26550ca1efa95347a354088 | LarisaOvchinnikova/Python | /Unit test, decorators/example/timer.py | 457 | 3.703125 | 4 | import time
def timer(func, x, y):
start = time.time()
result = func(x, y)
end = time.time() - start
print("Time elapsed ", round(end, 3))
return result
def add(x,y = 10):
time.sleep(0.5)
return x + y
def sub(x,y):
time.sleep(0.5)
return x - y
def mul(x,y):
time.sleep(0.5)
... |
855ba74add997a86ac15e0e9627cc3b1fb1ff388 | LarisaOvchinnikova/Python | /1 - Python-2/19 - arguments/from lesson.py | 752 | 4.28125 | 4 | # def func(x=10, y=20): #дефолтные значения без пробелов
# return x + y
#
# print(func(8, 5)) # 13
# print(func(12)) # 32
# print(func()) # 30
# def func(x, y, z=1): # все дефолтные справа
# return (((x, y),) * z)
#
# print(func(1,2,3)) #((1, 2), (1, 2), (1, 2))
# print(func(1,2)) # ((1, 2),)
# def func(... |
14bae1225666bd8872b19cd3d3b99cd7bc7de1b5 | LarisaOvchinnikova/Python | /1 - Python-2/5 - Types of data(lists, tuples...)/HW5/1. Filter a list I.py | 205 | 3.5 | 4 | def filter_len(lst):
arr = [el for el in lst if len(el) < 5]
return arr
items = ['Apricot', 'Cat', 'Dog', 'Ocelot', 'Zebra', 'Bat', 'Orange']
filtered_list = filter_len(items)
print(filtered_list) |
4cfd06f561f12b6089deb51f2177b8e9337bc34c | LarisaOvchinnikova/Python | /1 - Python-2/1 - variables, input, print/1 - feet to meters.py | 104 | 3.9375 | 4 | feet = float(input("How many feet? "))
meters = round(feet * 0.3048, 2)
print(f"It\'s {meters} meters!") |
931a40a6f9332e6e211d26c56a24510970672871 | LarisaOvchinnikova/Python | /tasks for students/calculator with button.py | 3,159 | 3.78125 | 4 | # 1)импортируем нужную библиотеку
# 2)создаем окно
# 3)создаем кнопки
# 4)создаем калькулятор:
# а)исключаем возможность введения букв
# б)добавляем влзможность счета 9основная часть программы)
# в)добавляем кнопку очистить
#from terminal run: python -m tkinter
# 1)импортируем нужную библиотеку
from tkinter import *... |
4cb472a1b0b9693624bc05778d942ccc8e0c9862 | LarisaOvchinnikova/Python | /1 - Python-2/17 - Обработка исключений, CLASSES/HW17/1. Book Shelf.py | 506 | 3.703125 | 4 | class Book:
title = ""
author = ""
def get_title(self):
return f"Title: {self.title}"
def get_author(self):
return f"Author: {self.author}"
HP = Book()
HP.title = "Harry Potter"
HP.author = "J.K. Rowling"
print(HP.get_title())
print(HP.get_author())
TS = Book()
TS.title = "The Adven... |
0ab9f69dceed7ecc5f20796a8922623be65c6f29 | LarisaOvchinnikova/Python | /HW5/Drunk Say_helloNew1.py | 301 | 3.859375 | 4 | def drunk_say_hello(name):
name = list(name)
res = "Hello "
for i in range(len(name)):
if i % 2 == 0:
res = res + name[i].upper()
else:
res = res + name[i]
return ''.join(res)
name = input("Enter your full name: ")
print(drunk_say_hello(name))
|
1c92205d3ecccdac19e5b726682d497868a3ed73 | LarisaOvchinnikova/Python | /HW13 try catch exceptions/2 - Practice exceptions.py | 650 | 4.03125 | 4 | def positive_divide(a, b):
try:
result = a / b
if result < 0:
raise ValueError("Cannot be negative")
return result
except ZeroDivisionError:
return 0
except TypeError as error:
return "Type Error!!!!!!"
print(error)
# print(positive_divide(1, 2))... |
f7d5ef541091dcc376f3fce145aacce7842e3437 | LarisaOvchinnikova/Python | /1 - Python-2/14- Read the book and create new file for every chapter/read the book.py | 861 | 3.5625 | 4 | import os
os.mkdir("Harry Potter Book 1") # create new directory
book = open("harry potter and the sorcerer's stone.txt")
text = book.readlines()[3:] # skip first 3 empty lines
buffer = []
chap_count = 1
for line in text:
if line.startswith("CHAPTER") and not line.startswith("CHAPTER ONE"):
file_name ... |
04f9664ad8d43e67c386a917ee8b28127b32315d | LarisaOvchinnikova/Python | /1 - Python-2/4 - strings functions/Determine the properties of a string.py | 1,124 | 4.25 | 4 | #Print word " has lowercase letters" if it has only lowercase alphabet characters
# Print word " has uppercase letters"
# if it has only uppercase alphabet characters
# Print word " has so many letters. Much wow."
# if it has both uppercase and lowercase alphabet characters but no digits
# Print word " has digits" if
#... |
9d30dada7480e710f0b76cfb69b438de55afb790 | LarisaOvchinnikova/Python | /Loops/loop.py | 1,829 | 3.734375 | 4 | # ----------------------------for ------------------------
colors = ["red", "green", "blue"]
for elem in colors:
print(elem)
elem = elem.capitalize()
print(f"I like {elem}")
for i in range(len(colors)):
print(i)
print(colors[i])
if i == 1:
colors[i] = "white"
# ----------------------
... |
6902167f4f870729dd8f5adae6d8781af24cc550 | LarisaOvchinnikova/Python | /HW5/Draw a ladder.py | 199 | 3.6875 | 4 | def ladder(n):
str = ''
for i in range(n):
if i != n:
str = str + '#' * (i + 1) + '\n'
else:
str = str + "#" * (i + 1)
return str
print(ladder(4))
|
c144310e9b45abcdbd3f21baf5c3d65fc2cf895f | LarisaOvchinnikova/Python | /1 - Python-2/10 - unit tests/HW10(unit testing)/1. Convert string to camel case.py | 305 | 3.6875 | 4 | https://www.codewars.com/kata/517abf86da9663f1d2000003
def to_camel_case(text):
text = text.replace("-"," ").replace("_"," ").split()
return "".join([el.title() if i > 0 else el for i, el in enumerate(text)])
print(to_camel_case("the-stealth-warrior"))
print(to_camel_case("The_Stealth_Warrior")) |
835304b10d3ad012fa746a6d53aae903db234083 | LarisaOvchinnikova/Python | /1 - Python-2/5 - Types of data(lists, tuples...)/HW5/8. Create a function that counts a Fibonacci Sequence.py | 268 | 3.953125 | 4 | def fibonacci(n):
if n == 0:
return []
elif n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-2] + fib[i-1])
return fib
print(fibonacci(0))
print(fibonacci(1))
print(fibonacci(2))
print(fibonacci(10)) |
33942f3c0706e1f17e4c87e12e54d875e594c0ca | LarisaOvchinnikova/Python | /HW8 + mini bank app/5 - Sum Fractions.py | 263 | 3.5625 | 4 | def sum_fractions(fraction):
s = 0
for el in fraction:
s = s + el[0] / el[1]
return round(s)
print(sum_fractions([[18, 13], [4, 5]]))
print(sum_fractions([[36, 4], [22, 60]]))
print(sum_fractions([[11, 2], [3, 4], [5, 4], [21, 11], [12, 6]])) |
123c29de54036dd9f87cde3c3e3283d556dbb297 | LarisaOvchinnikova/Python | /1 - Python-2/14 - os module, files, collections/HW14/Average Word Length.py | 271 | 3.90625 | 4 | def average_word_length(arr):
lst = [len(word) for word in arr]
s = sum(lst) / len(lst)
return round(s, 2)
# lst = ["banana", "apple", "grape", "mom", "a"]
f = open("most_common_words.txt")
lst = f.read().split()
f.close()
print(average_word_length(lst)) |
24e4535ec1c8f6b5015ec8009ed3944dfa36bf93 | LarisaOvchinnikova/Python | /HW5/Drunk Say_hello111.py | 628 | 3.796875 | 4 | def drunk_say_hello(name):
lst = name.split(' ')
res = "Hello "
for i in range(len(lst)):
if i == 0:
for j in range(len(lst[i])):
if j % 2 == 0:
res = res + lst[i][j].upper()
else:
res = res + lst[i][j].lower()
... |
ffc0627ca115c75b63dee63034b4a6c27b399a77 | LarisaOvchinnikova/Python | /arrays/lesson 27 april.py | 408 | 3.96875 | 4 | lst = [1,2,3,4,5,6]
if 6 in lst: # проходит по всему списку
print("yes")
print(lst[5]) # works quickly
lst = {1,2,3,4,5,6}
if 5 in lst: #работает очень быстро без прохода циклом по сету
print("yes")
print(hash("from"))
arr = [1,2,3,4]
if type(arr) == list:
s = "".join([str(el) for el in arr])
... |
6f276eac15ebf4813598a2fc867dbac8843b69d9 | LarisaOvchinnikova/Python | /Sets/sets from lesson.py | 2,564 | 4.5 | 4 | # set is unordered(unindexed), mutable collection of data items
# (items - inmutable - numbers, strings, tuples, boolean)
# set contains only unique values
x = {1, "hello", 3, 5, "world"}
print(len(x))
# to create new empty set, use set() function
x = set()
#length of the set
print(len(x)) # ---> 0
x = {1,1,1,1}
... |
5591bb790ea136bfe2145cf8b0dee3c61af20ab1 | LarisaOvchinnikova/Python | /games on Python/Игра крестики-нолики.py | 2,454 | 3.90625 | 4 | table = [
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']
]
def draw():
# Draw table
# -------------
# | - | - | - |
# -------------
# | - | - | - |
# -------------
# | - | - | - |
# -------------
print("-" * 13)
for row in table:
for cell in row:
... |
efbd0ff79e925471e7eafd0a1b1a309f4f8c716d | LarisaOvchinnikova/Python | /HW2/1 - mealPrice.py | 266 | 3.9375 | 4 | mealPrice = float(input("input meal price "))
tipPercent = int(input("input tip percent "))
taxPercent = int(input("input tax percent "))
mealCost = mealPrice + mealPrice * tipPercent / 100 + mealPrice * taxPercent / 100;
print(f"Total cost: ${round(mealCost, 2)}")
|
13c0fee2a8489e33dbb7de72df60e50ce9cf1a9a | LarisaOvchinnikova/Python | /1 - Python-2/6 - List Comprehensions/HW6/1 - a filtered list of elements which start with an uppercase letter..py | 189 | 3.828125 | 4 | lst = ['Apricot', 'cat', 'Dog', 'ocelot', 'Zebra', 'bat', 'orange']
filtered_list = [el for el in lst if el[0].isupper()]
print(filtered_list)
#filtered_list = ['Apricot', 'Dog', 'Zebra']
|
bf03eb1d65d2ffec270d9fd045753477fa1c7eaa | LarisaOvchinnikova/Python | /tasks for students/draw stars pattern.py | 553 | 4.0625 | 4 | # *****
# *****
# *****
for i in range(3):
print("*" * 5)
# -----------------------------------------
# triangle
# *
# **
# ***
# ****
# *****
for i in range(5):
print("*" * i)
# ------------------------------------------
# ****
# ***
# **
# *
# triangle
for i in range(5, 0, -1):
print("*" * i)
# --------... |
b77cb65f8933f688bc4c6e4b173f16a1f6243f71 | Ameykolhe/LP-3 | /ICS/Assignment2/Utilities.py | 3,726 | 3.515625 | 4 | #Utilities Required
#1 S-box
S_box={
"0000":"1001",
"0001":"0100",
"0010":"1010",
"0011":"1011",
"0100":"1101",
"0101":"0001",
"0110":"1000",
"0111":"0101",
"1000":"0110",
"1001":"0010",
"1010":"0000",
"1011":"0011",
"1100":"1100",
"1101":"... |
10cfb093d28baec10fb9e597f077750d613d2940 | vmoktali/rosalind_solutions | /rosalind_solutions/rev_complement.py | 414 | 3.984375 | 4 | #!/usr/bin/python
import re
def replace_all(repls, str):
return re.sub('|'.join(re.escape(key) for key in repls.keys()),
lambda k: repls[k.group(0)], str)
dna = raw_input("Enter the DNA string:")
rev_dna = replace_all({"A... |
24752da8dfbe0a194ce884389c678ffe1c895740 | bruzecruise/Intro_Biocom_ND_319_Tutorial7 | /exercise 7.py | 2,091 | 3.5625 | 4 | #exercise 7#
#Dan Bruzzese and Zoe Loh
# question 1
import pandas
from plotnine import *
File=open("Lecture11.fasta","r")
plotData = pandas.DataFrame(columns = ["Sequence Length" , "GC content"])
for line in File:
line = line.strip()
if ">" in line:
continue
else:
#First the length of ... |
9f62bc48fc88391ffee18e9d18e341307cb01233 | youjiahe/note | /15.Python/nsd1806/python/day06/mygui2.py | 720 | 3.703125 | 4 | import tkinter
from functools import partial
#
# def hello():
# lb.config(text="Hello China!")
#
# def greet():
# lb.config(text="Hello Tedu!")
def welcome(word):
def say_hi():
lb.config(text='Hello %s!' % word)
return say_hi
root = tkinter.Tk()
lb = tkinter.Label(root, text='Hello World!', f... |
b7db6b98df8c31d0671ac1b1095e9b9c82b95044 | youjiahe/note | /15.Python/nsd1806/python/day08/mydate.py | 707 | 3.75 | 4 | class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def create_date(cls, str_date):
y, m, d = map(int, str_date.split('-'))
instance = cls(y, m, d)
return instance
@staticmethod
def is_dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.