blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
06129f5dd4fc8976370406d05bb3ebd6e4a18ac5 | EvelynWangai/RSA-Encryption-Decryption | /encryption.py | 1,415 | 4.3125 | 4 | # library to be imported
import math
# creating my ditionary
my_dict={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,
'm':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,
'y':25,'z':26,' ':27}
## Creating RSA keys and encrypting a message
def ... |
6096573b96a0d60f8fd9d89ed44965cadf705c3d | zzjumperzz/PythonLearning | /FLishC/class23.py | 797 | 3.859375 | 4 | #斐波那契函数
#使用迭代方式实现(自己完成的,闭包方式)
def function(n):
def one():
nonlocal n
sums = [1,1]
for i in range(2,n):
sum=sums[0]+sums[1]
sums[0]=sums[1]
sums[1]=sum
return sum
return one()
#n = int(input('请输入一个正整数:'))
n=30
if n <= 2:
print('%d的斐波那契值是%d'%... |
4b49217ad7381a4f2c3d7f691daea01773b75057 | zzjumperzz/PythonLearning | /FLishC/class24.py | 221 | 4.0625 | 4 | #汉诺塔实现
def hanoi(n,x,y,z):
if n==1:
print(x,'-->',z)
else:
hanoi((n-1),x,z,y)
print(x, '-->', z)
hanoi((n-1),y,x,z)
n=int(input('汉诺塔层数:'))
hanoi(n,'x','y','z') |
2b1cf43d9daff14b4dbefd34a5607d640de5f4b6 | ajay2java2dev/mcs-ds | /cs498_applied_machine_learning/hw2/hw2-gradient-descent.py | 681 | 3.9375 | 4 | import numpy as np
def gradient_descent(x,y):
print('testing gradient descent')
m_curr = b_curr = 0
iterations = 10000
n = len (x)
learning_rate = 0.08
for i in range (iterations):
y_predicted = m_curr * x + b_curr # y = mx + b
cost = (1/n) * sum ([val**2 for va... |
53e1ba2e72dd55fd19806968fd8300254e8cc112 | Gogka/ANN | /ANN.py | 1,655 | 3.640625 | 4 | from ANNLayer import *
class ANN():
### Class Artificial Neural network ###
# Initializing
def __init__(self, layers):
self.layers = layers
# Method for getting result from network
def think(self, inputs, layer_index = 0):
current_layer = self.layers[layer_index]
if layer... |
08be49a22c49b89489e1e00abacaa0d186661370 | mdonahoe/Puzzles | /letterpress.py | 2,285 | 3.609375 | 4 | """
A letterpress cheater
What is the longest word we can spell using 25 letter tiles?
"""
import random
import string
import time
timings = {}
def track(f):
def g(*args, **kwds):
t = time.time()
ret = f(*args, **kwds)
v = time.time() - t
k = f.__name__
timings[k] = timing... |
b38d8e8f28ef2ecc514cd67735f3a96a5686d2cf | wroblewskiwojciech161/BeerCompiler | /objects.py | 1,134 | 3.71875 | 4 |
class Variable():
def __init__(self, name):
self.name = str(name)
self.value = None
self.address = None
self.declared = False
self.iterator = False
# if iterator stre the addresses of iteration
self.lowerBound = None
self.upperBound = None
sel... |
2dd610d2a3b488af484cbac5d1d7ddb97f83e303 | writeforsajid/PythonResource | /cross_validation/cross_validation.py | 604 | 3.734375 | 4 | """
===============================================
Objective: Cross validation implementation
Author: Anber Arif
Blog: https://dataaspirant.com
Date: 2020-12-03
===============================================
"""
## k-fold cross validation demonstration by scikit-learn library
from numpy import array
from sklearn.mo... |
e00e9a16f71001ff26c6172ba11c44a52226a53d | AhmadIssaAlaa/SequentialHearstPatterns | /common/parsed_sentence.py | 1,539 | 3.515625 | 4 | class parsed_sentence:
def __init__(self):
self.words = []
self.NPs = []
def add_word(self, w, l, pos, i, par, parent_index, rel , ty):
word = parsed_word(w, l, pos, i, par, parent_index, rel, ty)
self.words.append(word)
def add_NP(self, np, root, ri, start, end):
... |
ba3f835f5e62a4af052a82524a6ecd5dcfe8636d | gvanrossum/patma | /examples/expr.py | 10,930 | 3.625 | 4 | # Sample program that incorporates many uses of `match`.
from collections import namedtuple
from dataclasses import dataclass
from enum import Enum
import re
import sys
import tokenize
class TokenStream:
"""Class representing a consumable stream of input tokens"""
def __init__(self, input):
lines = ite... |
05ae074235d92473ff5a729217e00b97c6f6bdbe | cloi1994/lcsumup | /code/backtracking/code/bfs/WordLadder.py | 1,137 | 3.5625 | 4 | class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
step = 0
l = len(beginWord)
q = [beginWord]
if endWord not in w... |
de5508cf72a12b2584c7d2dfacbd8008e627b53f | jack-sneddon/python | /07-lists/list-comprehention.py | 259 | 3.921875 | 4 | # a list comprehention combines the for loop and the creation of new elements inot the one line, and automatically append each new element.
squares = [value**2 for value in range (1, 11)]
print (squares)
# <<list-name>> = [<<expression>> - << for loop >>]
|
399106fc8885d5f892d49b080084a393ab5dbb4a | jack-sneddon/python | /04-lists/list-sort.py | 596 | 4.46875 | 4 |
# sort - changes the order permenantly
cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla']
cars.sort()
print (cars)
# reverse sort
cars.sort(reverse = True)
print (cars)
# temporary sort - sorted
cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla']
print("here is the original list:")
print (cars)
print("here is ... |
e7f972375ba19e5060b271fc4de2db58cfd317c7 | jack-sneddon/python | /30-data/pandas/box_chart.py | 1,615 | 4.1875 | 4 | # $ pip3 install pandas
# pip3 install matplotlib
# https://www.geeksforgeeks.org/data-visualization-different-charts-python/
# import pandas and matplotlib
import sys
import pandas as pd
import matplotlib.pyplot as plt
### Same code from Dataframe as other charts ###
# create 2D array of table given above
dat... |
9ac9387df4e40b7d634822b87509094f5d9f1f26 | jack-sneddon/python | /17-json/json-write.py | 591 | 3.9375 | 4 | # save data to json file
import json
# save a list of numbers
numbers = [2, 3, 4, 5, 11, 13]
filename = '../out/numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)
# save a name
username = input("What is your name? ")
filename = '../out/username.json'
with open(filename, 'w') as f:
json.dump(... |
907779a086b3407dbb3ae24b936f7d79cea6e225 | jack-sneddon/python | /26-cvs/read_csv.py | 1,459 | 3.71875 | 4 | import csv
import os
'''
using reader and writer read and writes rows using lists
DictReader and DictWriter do the same thing, but use dictionaries
and the first row is the key
'''
# setup
bond_villian_file = "~/villians.csv"
if os.path.isfile(bond_villian_file) :
os.remove(bond_villian_file)
# w... |
b73966daf46e7c5cc5b7adaf69b40ef48e483759 | jack-sneddon/python | /03-math/math_operations.py | 1,278 | 3.796875 | 4 | # math play
#
# print numbers
#
myNumber = 125
print("[print via str()]\n\t" + str(myNumber))
print("[print via %% operator]\n\t%s" %myNumber)
print("[print via format function]\n\t{}".format(myNumber))
print(f'[print via f function\n\t{myNumber}')
# integers
print('[operators]')
myInt1 = 10
myInt2 = 5
myAdd = myIn... |
ae3b37f48043bd2e6c2ed8f5b409e253d95963b5 | jack-sneddon/python | /26-cvs/read_with_headers.py | 1,239 | 3.890625 | 4 | import csv
import os
example_with_headers_file = "../files/exampleWithHeader.csv"
example_without_headers_file = "../files/example.csv"
#Setup
if os.path.isfile(example_with_headers_file) :
print("read " + example_with_headers_file)
else :
print("Error: file missing: " + example_with_headers_file )
if os.pat... |
9a6c909e0fec1e2b90318ed7644d97e8a1663182 | jack-sneddon/python | /04-lists/lists-while-loop.py | 2,007 | 4.40625 | 4 | # a for loop is effective for looping through a list, but you shouldn't modify a
# list inside for loop because Pything will have trouble keeping track of the items
# in the list. To modify a list as you work throuh it, use a while loop.
# Using while loops with lists and dictionaries allows you to collect, store, ... |
fd9887ec0412e75bc0a8a516652eefa2255fce04 | jack-sneddon/python | /20-bitwise/bitcheck.py | 286 | 3.859375 | 4 | def bits(n):
while n:
b = n & (~n+1)
yield b
n ^= b
value = input("enter a number: ")
number = int(value, 10)
for b in bits(number):
print(f"{b}")
print("\n")
print(f"{bin(number)}")
# 1000000000000000000000000000010000000000000000000000001000010010 |
20fe35ed8a64b51f85be3849302dcbcf82459d57 | GeoMukkath/python_programs | /python_programs/practice2x[1].py | 433 | 3.703125 | 4 | class profile:
def __init__(self):
self.name = "Geo";
self.age = 23;
def update(self):
self.age = 23;
def compare(self,candidate2):
if self.age == candidate2.age:
return True;
else:
return False;
candidate1 = profile();
candidate2 = profile();
candidate2.update();
candidate2.name = "Rohi... |
41be0de1416908cd805e286c5796052e725a60b1 | GeoMukkath/python_programs | /All_python_programs/fibonacci.py | 174 | 4.3125 | 4 | #Q. Program for fibonacci sequence
n = int(input("Enter how many times the sequence must be generated: "));
l = 1;
num =0;
for i in range(n):
num = num +l;
print(num);
|
17ff6eaf25026ada4fd159e2ae3905854fd56d2f | GeoMukkath/python_programs | /All_python_programs/max_among_n.py | 280 | 4.21875 | 4 | #Q. Find the maximum among n numbers given as input.
n = int(input("Enter the number of numbers : "));
print("Enter the numbers: ");
a = [ ];
for i in range(n):
num = int(input( ));
a.append(num);
maximum= max(a);
print("The maximum among the given list is %d" %maximum); |
a6ca1f16c1dcf4787e0a5e7274818aa25b1967a3 | GeoMukkath/python_programs | /python_programs/practice4x[1].py | 555 | 3.765625 | 4 | class student:
college ="FCRIT" ;
def __init__(self,m1,m2,m3):
self.m1 = m1 ;
self.m2 = m2 ;
self.m3 = m3 ;
self.lap = self.laptop()
def avg(self):
return (self.m1 + self.m2 + self.m3) / 3
@classmethod
def info(cls):
return cls.college ;
class laptop:
def __init__(self,brand,ram,bi... |
b319e5712358bfaa9b926ff8af550a6623d6b313 | uthpalaherath/MatSciScripts | /plotdata.py | 2,162 | 3.609375 | 4 | #!/usr/bin/env python
""" Plot data from csv files.
This script generates plots from data retrieved
from csv or similar text based files.
Author: Uthpala Herath
Usage:
Enter plotdata.py -h for help.
"""
import argparse
import os
import sys
from argparse import RawTextHelpFormatter
import matplotlib.pyplot as p... |
b9a895f074168c0be5f86592214a316b46bbc98b | JLarraburu/Python-Crash-Course | /Part 1/Hello World.py | 1,574 | 4.65625 | 5 | # Python Crash Course
# Jonathan Larraburu
print ("Hello World!")
# Variables
message = "Hello Python World! This string is saved to a variable."
print(message)
variable_rules = "Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a n... |
6e2be3afb6a80f2f263d149e34e55f278781d9aa | zarrinan/tmsdne_fe_api | /tms/plotly_chart.py | 3,816 | 3.65625 | 4 | def get_chart_url(day, api_key):
'''Generates a plotly chart and returns its url
Day in format "YYYY-MM-DD"
Parameters: Day, Plotly API key
Returns: Plotly chart url'''
import pandas as pd
import numpy as np
import datetime
from pandas_datareader import data as pdr
import... |
8a9c342d68a93b82f2118ebf4f542bb37ad95446 | Infinite-Loop-KJSIEIT/Algo-Talks | /Linked List/Medium/detect_cycle.py | 1,256 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
"""
Link : https://leetcode.com/problems/linked-list-cycle-ii/
Solution by Keshav Mishra
"""
# Approach 1
# O(N) - Space
class Solution:
def detectCycle(self, head: ListNode) -> Li... |
7bccd579f89e41a3402401a784a54a271b8e9d3e | kahee/Python-Study | /data_structure/sort/quick_sort.py | 1,172 | 3.984375 | 4 | def quick_sort(list):
if len(list) <= 1:
return list
else:
pivot = list[0]
less = [i for i in list[1:] if i <= pivot]
greater = [i for i in list[1:] if i > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
def partition(list, start, end):
pivot = list... |
cae06ec7c1df47570276ee34b144ad85c5f1e09a | kahee/Python-Study | /data_structure/CH3/list-stack.py | 434 | 4.125 | 4 | def push(item):
stack.append(item)
def peek():
# top 항목 접근
if len(stack) != 0:
return stack[-1]
def pop():
# 삭제 연산
if len(stack) != 0:
# 리스트의 맨 뒤에 있는 항목 제거
item = stack.pop(-1)
return item
stack = []
push('apple')
push('orange')
push('cherry')
print(stack)
prin... |
8475376b5af3b195f3595c07b55b475f0fba02c2 | vzalygin/PyProj | /Tree.py | 4,084 | 3.859375 | 4 | class Dict:
def __init__(self):
self.root = None
def __getitem__(self, key):
return self.get(self.root, key)
def __contains__(self, key):
try:
self.get(self.root, key)
successful = True
except:
successful = False
return successful... |
d29a4b9d5ffc3e0a371bb430df639e9b5bf710e5 | vzalygin/PyProj | /IGOR.py | 362 | 3.53125 | 4 | ch = input()
ch_count = int(input())
x = ch_count-1
for __ in range(ch_count):
space_count = ch_count - 1 + x
for i in range(ch_count):
s = ''
for _ in range(space_count):
s = s + ' '
space_count -= 1
for _ in range(i * 2 + 1):
s = s + ch
print(s)
... |
2ae64ad6761328eff4e97dcb15cbdc44a3316538 | vzalygin/PyProj | /tasks/task3.py | 498 | 3.640625 | 4 | def perim(a, b, c):
return a + b + c
def canBe(a, b, c):
return a + b > c and a + c > b and c + b > a \
and a > 0 and b > 0 and c > 0
def main():
a, b, c = [int(x) for x in input().split()]
p = 0
if canBe(a, b, c):
p = perim(a, b, c)
with open('task3_out.txt', 'w') as f:
... |
2ecc0a48fb86e7120384b5aca54318e8ec4e4ec2 | vzalygin/PyProj | /1.py | 694 | 3.703125 | 4 | def empty(): return None
def join(x, lst): return (x, lst)
def is_empty(lst): return lst == None
def head(lst): return lst[0]
def tail(lst): return lst[1]
def to_ll(arr):
res = empty()
for i in range(len(arr)-1, -1, -1):
res = join(arr[i], res)
return res
def reverse(lst):
res = empty()
... |
54d43f48470a020c083f58e4931798a864fcd720 | fgnt/mms_msg | /mms_msg/sampling/utils/sequence_sampling.py | 949 | 3.734375 | 4 | import numpy as np
def sample_random_round_robin(a, sequence, rng: np.random.Generator):
"""
>>> a = list('abc')
>>> sequence = []
>>> rng = np.random.default_rng(42)
>>> for i in range(10):
... s = sample_random_round_robin(a, sequence, rng)
... sequence.append(s)
... prin... |
ac54c51e797e49400dc733935b1509b9f4553a49 | siegltomas/xsiegl_PV248 | /01-regexp/stat.py | 2,800 | 3.640625 | 4 | #!/usr/bin/env python3
import sys
import re
# delete years in brackets
def delete_years(str_with_years):
delete = False
str_without_years = ""
for c in str_with_years:
if c == '(':
delete = True
elif c == ')':
delete = False
elif not delete:
st... |
44d7281cf0dd948499eeb85c62b1f9d028ed23e5 | meganmastro/CS506Spring2021Repository | /mapc2/scripts/query_mlab_by_date.py | 4,974 | 3.625 | 4 | # This script queries the MLAB data on Google BigQuery at specific times,
# throughout a year. It then outputs the results to an output file
from google.cloud import bigquery
import pandas as pd
from datetime import date
import argparse
"""
Executes a query against the MLAB data on BigQuery, and
returns the results... |
8a94ec4d0f4fc73611f7f9b7b5bf08d743b6f5ed | itaknfp/c4-week6-persegilingkaran | /draw_rec_cir.py | 509 | 4.0625 | 4 | import turtle
if __name__ == "__main__":
print ('MEMBUAT PERSEGI')
a = int(input("Masukkan sisi: "))
n= turtle
n.shape('turtle')
n.color('red')
n.down()
n.forward(a)
n.left(90)
n.forward(a)
n.left(90)
n.forward(a)
n.left(90)
n.forward(a)
n.left(90)
n.penup()
b = int (input("masuk... |
c9c2548eb74b5375baeea0d7d526d0dd8446e653 | Varun-Mullins/Triangle567 | /Triangle.py | 1,623 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Updates on Friday January 31 2020
@author: Varun Mark Mullins
cwid:10456027
This file takes in three lengths of a triangle and checks the validity of the triangle and returns the type of
triangle and checks if it is a right angle triangle or not.
"""
def classifyTriangle(a, b, c):
""... |
95b20d7f67e8801a646523383179436d22c15a01 | liusong-cn/python | /file_about.py | 732 | 3.5625 | 4 | #coding=utf-8
"""学习文件相关操作"""
# 使用关键字参数避免设置其他不必要的参数
f = open('test/file_about.txt','w+',encoding='utf-8')
#多行文本
string = """ 今天是个好日子
明天放假
后天居然又上班了
"""
f.write(string)
import chardet #用于查看编码
#指定打开文件的编码
fin = open('test/file_about.txt','r',encoding='utf-8')
#迭代方式有几种,现在fin对象本身可迭代,因此可以直接使用下方方式,或者ite... |
5c7d3e4227aee84311717914ead661bc8145ed9f | liusong-cn/python | /pythonLearning/swan.py | 432 | 3.5 | 4 | # code=utf-8
# 测试类私有属性的访问
class Swan:
"""
类的私有属性通过双下划线表示
"""
__neck_swan = '天鹅脖子长'
def __init__(self):
print("__init__():", Swan.__neck_swan)
swan = Swan()
# 访问类的私有属性要么在类中访问,要么通过实例._类名__xxx
print("加入类名访问:", swan._Swan__neck_swan)
# print("不加类名访问:", swan.__neck_swan)
|
a48fe0cf2ca9b4bf5c2aef6dbf0bed866a009687 | shubhangi2803/Python-Projects | /Mastermind/Mastermind.py | 3,557 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import random
import pandas as pd
from itertools import permutations
from itertools import combinations
import array
#color=['Red','Yellow','Blue','Green','White','Black','Grey','Golden','Silver']
ran_colors=[]
color_num=[0,1,2,3,4,5,6,7,8]
##C=int(input... |
8f9de6617f089a70ac45e214091830c472fb78cb | Maaleenaa/AlleDaten | /SmartNinjaClasses/Class 8/examples/example_lists.py | 914 | 4.3125 | 4 | # initialize
newList = []
print newList
print #oder print list()
# append single elements - neue Elemente dazuhänge oder +=
newList.append('Banana')
print newList
print
# append add multiple elements with other lists
oldList = ['Milk', 'Honey']
shoppingList = newList + oldList
print shoppingList
print
# refe... |
42f21de63a3eff507c44d64f7d711ecd6c83d684 | gnsoares/UNICAMP_MC102_ProgrammingIntro | /lab12/lab12.py | 3,269 | 3.671875 | 4 | #!/usr/bin/env python3
ALTURA_TABULEIRO = 10
LARGURA_TABULEIRO = 10
# Funcao: atualiza_posicao
#
# Parametros:
# l: largura do bloco que ira cair
# a: altura do bloco que ira cair
# x: posicao horizontal inicial do bloco que ira cair
# desl: deslocamento horizontal a ser aplicado ao bloco (positivo p... |
ac349eb4da08279d11d242bf2bb67556729f4393 | zeirn/Exercises | /Week 4 - Workout.py | 815 | 4.21875 | 4 | x = input('How many days do you want to work out for? ') # This is what we're asking the user.
x = int(x)
# These are our lists.
strength = ['Pushups', 'Squats', 'Chinups', 'Deadlifts', 'Kettlebell swings']
cardio = ['Running', 'Swimming', 'Biking', 'Jump rope']
workout = []
for d in range(0, x): # This is ... |
322694778d780de62dfe28953325cb29ccf8b2eb | maurobaraldi/python-algorithms | /data_structures/linked_lists/doubly_linked_lists.py | 1,741 | 3.9375 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, data, prev=None, next=None):
self.data = data # Assign to node data
self.next = next # Assign to node next node
self.prev = prev # Assign to node previous node
class DoublyLinkedList:
def __init__(self):
self.head = Non... |
356b2d57e97260fca885cbdc9926fcdea139389e | maurobaraldi/python-algorithms | /algorithms/compression/rle/rle.py | 576 | 3.96875 | 4 | #!/usr/bin/env python3
def encode(text):
"""Encode text using Run-Length Encoding algorithm"""
res = []
counter = 1
for i in range(1, len(text)):
if text[i] == text[i-1]:
counter += 1
else:
res += [str(counter), text[i-1]]
counter = 1
res += [str(... |
5dd910cb4bf25032525686d34e613494ded01aff | maurobaraldi/python-algorithms | /tests/data_structures/queue/test_queue.py | 957 | 3.609375 | 4 | #!/usr/bin/env python
import unittest
from data_structures.queue.queue import Queue
class TestQueue(unittest.TestCase):
def setUp(self):
self.queue = Queue(1)
def test_instantiate_a_queue(self):
self.assertIsInstance(self.queue, Queue)
def test_queue_is_full(self):
self.assertFa... |
5603ea48356666642ae671d8f54b927a42185735 | code-in-the-snow/simple | /SIMPLE/gameApp.py | 2,299 | 3.6875 | 4 | # 11-12-2015
# gameApp.py
# This is a class to run a simple guessing game. OO design. Meant to be
# easily extensible to more complicated game.
from random import randint
import pdb
class GameApp:
def __init__(self, interface):
self.goal = randint(1, 10001)
self.guess_count = 0
self.... |
6a9a05b6bd1321b78e78f42ea5cb25ea5d52be12 | alanchn31/Four-Pillars-of-Object-Oriented-Programming | /Attributes and Methods/init_eg.py | 1,228 | 4.03125 | 4 | #An attribute is a property that further defines a class
#A method is a function within a class which can access all the attributes of a
#class and perform a specific task
#Class attributes are sttributes that are shared across all instances of a class
#They are created either as a part of the class or by using class... |
b3b41256f0ad71481c6aca36ea45ad3a85dc7f9c | alanchn31/Four-Pillars-of-Object-Oriented-Programming | /Polymorphism - Final Pillar/overloading.py | 279 | 3.875 | 4 | class Square:
def __init__(self,side):
self.side = side
def __add__(squareOne, squareTwo):
return ((4*squareOne.side) + (4*squareTwo.side))
squareOne = Square(5)
squareTwo = Square(10)
print("Sum of sides of both the squares = ", squareOne + squareTwo)
|
f71412630c155fe33c367f29ac3a5015a22fc70f | esizemore/Homework-2 | /Sizemore_hw2_prob1 | 1,896 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 5 19:24:39 2017
@author: elizabethsizemore
"""
#distance in lightyears
x=int(input("Enter the distance between a spaceship and another planet in lightyears:"))
#distance converted to meters
x2=9.461E15*x
#velocities in m/s
v=float(input("Enter... |
44cc43882d6c93bfca446996c011c11b24273155 | Jam0134/Python-Challenge | /PyBank/.ipynb_checkpoints/main-checkpoint.py | 873 | 3.640625 | 4 |
import os
import csv
# Specify the file to write to
output_path = os.path.join( "Resources", "budget_data.csv")
total_months = 0
# Open the file using mode. Specify the variable to hold the contents
with open(output_path) as financial_data:
# Initialize csv.reader
csvreader = csv.reader(financial_data, del... |
c90383c0cbf44fa216d4638138b43af14a5905a5 | dizhaung/Elusive | /log_generator/generators/generator.py | 798 | 3.53125 | 4 | import threading
import sys
import time
class LogGenerator:
def __init__(self, sleep = 1):
self.generators = []
self.sleep = sleep
def add_generator(self, generator):
self.generators.append(generator)
def generate(self):
while True:
time.sleep(self.sleep)
... |
3dac44290594bfda96f84ff281880fd11358ac1a | nishikaverma/Python_progs | /tuple_unpack.py | 323 | 3.734375 | 4 | album=("ashiqui 2",2013,"arijit singh",((1,"tum he ho"),(2,"chahu mai ya na",(3,"meri asiqui"),(4,"aasaan nahi")))
Title,year,singer,songs=album
print("title",Title)
print("year",year)
print("singer",singer)
for x in songs:
print("song no.:{0},song name:{1}".format(x[0],x[1]))
... |
f8718009881c2582b0703261f336849f30f07f91 | nishikaverma/Python_progs | /Python GUI samples progs/listbox 02.py | 1,523 | 3.828125 | 4 | '''from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
obj=Tk()
obj.geometry("400x400")
def execute():
enter=simpledialog.askstring("input","Enter item no.",minvalue=1,maxvalue=list.size())
if type(enter) is int:
item=list.get(enter-1)
lab.config(text="your sele... |
d343aff3531cf504862070f308fc8646344945f8 | nishikaverma/Python_progs | /ptyhton progs with oop concepts/class_emp.py | 492 | 3.734375 | 4 | class employee:
def __init__(self,age,name,salary):
self.his_age=age
self.his_name=name
self.his_sal=salary
print("init called")
E=employee(45,"sagar",39000.0)
print("age is",E.his_age,"name is",E.his_name,"salary is",E.his_sal)
F=employee(29,"amit",20000.0)
print("age is",... |
09e478fce9dbc09508770145167ae609b26e8ede | nishikaverma/Python_progs | /python exception handeling programs/exception00.py | 372 | 4.09375 | 4 | while True:
try:
a=int(input("enter an integer"))
b=int(input("enter another integer"))
c=a/b
except ZeroDivisionError:
print("please enter a non zero denominator!")
except ValueError:
print("please enter only integer value!")
else:
... |
37899374fa68b1a513b0d484b0a9ae4a18fe9dbe | nishikaverma/Python_progs | /python progs --TOC/TOC exp 8 -Tm.py | 1,534 | 3.828125 | 4 | ##################################################################
#Program which will increment the given binary number by 1.
##################################################################
class TM:
def __init__(self,lst):
self.lst=lst
self.head = -1
def validate(self):
if l... |
e265203d5aa75d3470e623b948ee646f5fab9f55 | nishikaverma/Python_progs | /dictionary_comprihensaon04.py | 117 | 4.03125 | 4 | dict1={"a":1,"b":2,"c":3,"d":4,"e":5}
dict2={k:"even" if v %2==0 else "odd" for (k,v) in dict1.items()}
print(dict2)
|
71e33c49c5876ead8a444172a2cb8fb41e4611a6 | nishikaverma/Python_progs | /variable_len_argument.py | 224 | 4.0625 | 4 | def find_largest(*t):
max=0
large=''
for x in t:
if len(x)>max:
max=len(x)
large=x
return x
print("the largest strin among them is ",find_largest("january","feb","augusth"))
|
829cbd0b8bb2bd16c9384854d5627f66708d983b | nishikaverma/Python_progs | /dictonary_players.py | 351 | 3.78125 | 4 | players={}
i=1
while i<=5:
name=input("enter name ")
runs=int(input("enter the runs they made "))
players[name]=runs
i+=1
print("list of players:rums is:" ,players)
hs=0
maxm=""
for playr,run in players.items():
if run>hs:
hs=run
maxm=playr
print("highest score is:... |
a8f0df887a8e6d08e9342efe3a99367fb341192c | nishikaverma/Python_progs | /num_guessing_game.py | 693 | 3.796875 | 4 | a=10
i=int(input("guess the no.!!!!!!!\n..."))
if(i==a):
print('congratulation! you have guessed it correctly.')
while i!=a :
print('[FOR QUITTING THE GAME TYPE 0OR A NEGTAIVE NO.]')
if(i!=a):
if(i>a):
print('sorry! wrong guessing. no. is too large.')
elif(0<i<a):
... |
3fabbb43a1ec5a8fd57833b20d33f39979bac6e3 | nishikaverma/Python_progs | /Python multithreading progs/multithreading4.py | 852 | 4.03125 | 4 |
# multithreading by making object if Thread class
import threading
def show1(): # execution handeleled by Thread 1
for i in range(10):
print("good")
print("this execution is handeled by",threading.current_thread().getName())
def show2(): # execution handeleled by Thread 2
for i in range(10):
... |
c9d0d7d50e5b6e137d501bdce04a848522f2947f | nishikaverma/Python_progs | /find_largest01.py | 318 | 3.859375 | 4 | def find_largest(*s):
i=0
while i<=len(s):
for j in s[i]:
for j in range(1,len(s[i])):
count=count+1
i+=1
if(count>larg):
larg=count
print("thv elargest string among ",s,"s ",large)
find_largest("nishi","samarth","father")
|
2c8df53e232684544cedba656790723ecba69c65 | nishikaverma/Python_progs | /list03.py | 158 | 3.59375 | 4 | def square(mylilst):
sqlist=[]
for x in mylist:
sq=x*x
sqlist.append(sq)
print(sqlist)
mylist=[1,2,3,4,5]
print(square(mylist))
|
86a74ae2f3c313f7507f426b1993ae6b0432dea8 | nishikaverma/Python_progs | /python exception handeling programs/format_exc().py | 285 | 3.765625 | 4 | import traceback
while True:
try:
a=int(input("enter an integer"))
b=int(input("enter another integer"))
c=a/b
print("division is",c)
break
except(ZeroDivisionError,ValueError):
print(traceback.format_exc())
|
e8ad6f5cfa93b6e563234f9372c39d57d79096c1 | nishikaverma/Python_progs | /lambda_map()00.py | 179 | 4.25 | 4 | vowel=['a','e','i','o','u']
char=input("enter your name")
print("the vowels in your entered name are: ",list(filter(lambda char: "true" if for char in vowel else "false",char)))
|
e0e0f464f333c9d4b610bc810496396cfb9f7de8 | nishikaverma/Python_progs | /lambda00.py | 207 | 3.96875 | 4 |
name=input("enter name")
l=len(name)
print("last charactor of ur name is",(lambda str:str[l-1])(name))
#2nd way of coad
n=lambda str:str[len(str)-1]
print("the last charsctor of ur name is",n("nishika"))
|
b5de4a6a2982193a52336dd46c70447df4950b26 | nishikaverma/Python_progs | /ptyhton progs with oop concepts/class_variable00.py | 884 | 3.953125 | 4 | class Emp:
raise_amount=0
@classmethod
def set_raise_amt(cls):
cls.raise_amount=float(input("enter yhe increment percentage"))
def __init__(self,name ,age,sal):
self.name=name
self.age=age
self.sal=sal
def increse(self):
self.sal=self.sal+(self.sal*E... |
31e1eae9b6690cc4de688e6937f05f19de19f4bb | nishikaverma/Python_progs | /Python GUI samples progs/event handeling_button_0.py | 691 | 3.8125 | 4 | from tkinter import *
obj=Tk()
def redit():
l['bg']="red"
def blueit():
l['bg'] = "blue"
def greenit():
l['bg'] = "green"
b1=Button(obj,text="red",command=redit)
b2=Button(obj, text="blue",command=blueit)
b3=Button(obj,text="green",command=greenit)
l=Label(obj,bg="white",width=20,height=5)
'''
# this co... |
f00e7edd5240b74c72905823b62d432af7a1d948 | nishikaverma/Python_progs | /sortde().py | 338 | 3.921875 | 4 | mylist=[]
n=1
while n<6:
num=input("enter an integer")
mylist.append(num)
n=n+1
print("the list you entered is", mylist)
i=0
l=len(mylist)
while i<l:
j=i
while j<l:
if mylist[j]>mylist[j+1]:
mylist[i],mylist[j]=mylist[j],mylist[i]
j+=1
i+=1
print("the sorted... |
bdb9349af9771af4eea2ba6050b7473537454829 | nishikaverma/Python_progs | /user_register.py | 581 | 3.96875 | 4 | def askname():
while True:
name=input("enter your full name").strip()
if name.find(" ")!=-1:
return name
break
def askpass():
while True:
passw=input("enter password [should contain atleat 1 digit , atleast 1 uppe... |
cb2c07c1e73fb4a93f8df165124cf64434e5540a | spencerSunLingWei/Python_start_up | /lab2.py | 506 | 3.5625 | 4 | import math
def damped_oscillator_position(gamma, t, omega):
""" (num, num, num) -> (num)
This function takes in the damping coefficient (gamma), time (t) and the
angular frenquency (omega), it produces the position of the oscillator
at the given time.
>>> position = damped_oscillator_po... |
acd07430fbf0e9e87dec8c60dee9b49b65345a07 | spencerSunLingWei/Python_start_up | /lab8.py | 7,967 | 4 | 4 | class Matrix(object):
def __init__(self, matrix):
'''(Matrix, list)-> NoneType
creates a data attribute elements and instantiate it to the matrix.
Preconditions: list e contains 2 sublists, all the sublists in e have the same length.
Complete the instance variable definitions DO NO... |
ac129b091daf5351a9dd99175ef8a928a62ec80e | TakoLukava/HW_3 | /hw2_wk3.py | 86 | 3.65625 | 4 | import re
print(min((x for x in re.findall(r'\w+', input('enter:'))), key = len))
|
aa001a5aee1122b8efae4cfa7881964f418125b8 | Jinyiji/codingtest | /0821/31.py | 641 | 3.578125 | 4 | def solution(schedule):
answer = []
# idx는 schedule의 인덱스, i는 schedule의 값
# (서로 대응하는 idx, i에 대해)
for idx, i in enumerate(schedule):
if i == "X":
answer.append(idx+1)
return answer
# 아래는 테스트케이스 출력을 해보기 위한 코드입니다.
schedule = ["O", "X", "X", "O", "O", "O", "X", "O", "X", "X"]
ret = sol... |
22df7e2d6380000ab4f77c78f66f596b5d975383 | vinodkumavat/Numerical-Calculation | /4_Solution_to_Transcendental/1_QE.py | 847 | 3.84375 | 4 | import math
def OE(a, b, c):
D = b**2 - 4*a*c
root = -b/(2*a)
if D == 0:
print("Roots are equal and is ==> ")
print(f"\tRoot = {root}")
print(f"\tRoot = {root}")
elif D > 0:
alpha = root + (math.sqrt(D)/(2*a))
beta = root - (math.sqrt(D)/(2*a))
... |
64c93c5ac57bd30100ba84b111fbbb827490ea8e | vinodkumavat/Numerical-Calculation | /4_Solution_to_Transcendental/3_Bisection.py | 2,262 | 4.0625 | 4 | # It is also called as Bracketed method used when we know the boundary of solution
import math
def equation(x):
# y(x) = 0
y = math.exp(x) - 3
return y
def limitChanger(x_l, x_u):
y_l = equation(x_l)
y_u = equation(x_u)
x_m = (x_l + x_u)/2
y_m = equation(x_m)
if y_l*y_u ... |
787c3561e867bfee84370d9e186344c0801bb9f8 | TengCXXI/atbswp_misc_apps | /smcd.py | 4,816 | 3.9375 | 4 | #! python3
# smcd.py - (Selective Move/Copy/Delete) Allows user to move/copy/delete file(s) based on regex filter
# Created by Teng Mao @https://github.com/TengCXXI
import os, re, shutil, send2trash
import pyinputplus as pyip
from pathlib import Path
# Create a while loop to check for an absolute folder path ... |
506d6d8b2ef19a10fd77f6a088011af61eda8654 | mhcrnl/2019 | /python3webscraping/example_com/example_com.py | 1,426 | 3.734375 | 4 | """
author: mihai cornel mhcrnl@gmail.com
run: python example_com.py
program: test scraping the example.com site test
run: $ python example_com.py
DOC: https://docs.python.org/3/library/urllib.request.html#module-urllib.request
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
"""
impo... |
9591ab1592374725c95ece4a4f3ddb0abd707128 | TMcMac/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/101-lazy_matrix_mul.py | 1,596 | 3.859375 | 4 | #!/usr/bin/python3
""" A function to multiply two matracies """
import numpy as np
def lazy_matrix_mul(m_a, m_b):
"""
matrix_mul - a function to multiple two equally sized matracies
arg1: a matrix of integers or floats
arg2: a matrix of integers or floats
return - a new matrix of the products of ... |
49957748017b3d81cf2f8938e47146466a304454 | TMcMac/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 217 | 3.703125 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_matrix = []
def square(n):
return (n ** 2)
for row in matrix:
new_matrix.append(list(map(square, row)))
return new_matrix
|
22df2ad36fb027e09758146daddf8b8d4296d06b | TMcMac/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 271 | 3.65625 | 4 | #!/usr/bin/python3
"""Docstring"""
class MyList(list):
"""
Inherites from list
"""
def print_sorted(self):
"""
prints a sorted list
parameters - only self
"""
sorted_list = sorted(self)
print(sorted_list)
|
3186c75b82d1877db3efe13a8a432355503ec9f3 | TMcMac/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 526 | 4.28125 | 4 | #!/usr/bin/python3
"""This will get a line count on a text file"""
def number_of_lines(filename=""):
"""
A function to get a line count on a file
parameters - a file
"""
line_count = 0
with open(filename, 'r') as f:
"""
Opens the file as f in such as way that
we don't n... |
5c8df2051d971311883b58f15fbf17a1987655fd | TMcMac/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 831 | 4.46875 | 4 | #!/usr/bin/python3
"""Defines class square and takes in a size to intialize square"""
class Square():
"""Class Square for building a square of #s"""
def __init__(self, size=0):
"""Initializes an instance of square"""
self.size = size
def area(self):
"""Squares the size to get the ... |
599b735a88df520406b32eae4fe8a37026c885c6 | TMcMac/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 4,485 | 4.125 | 4 | #!/usr/bin/python3
"""Class Rectangle"""
from models import base
Base = base.Base
class Rectangle(Base):
"""
Class rectanlge, inherits from base
"""
def __init__(self, width, height, x=0, y=0, id=None):
"""
initializes an instance of rectangle
param1: width, non-zero pos int
... |
91ba75ce48c0cc3c02ffac8aaad19bbb093445aa | Faribairany/file_preprocessing-HoMLN- | /deleting_empty_row.py | 1,520 | 3.53125 | 4 | # import csv
# with open('unt_1.csv') as in_file:
# with open('unt_1_out.csv', 'w',newline='') as out_file:
# writer = csv.writer(out_file)
# for row in csv.reader(in_file):
# if any(row):
# writer.writerow(row)
# print('hello')
# import pandas as pd
# df =... |
b046953f263744a367a8c31143d2880fccb79e5c | TDD-Drayton/Python_Search- | /linearSearch.py | 506 | 3.796875 | 4 | #Python
thisList = ["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh"]
target = "aaa"
def linear_search(search_list, target_value):
matches = []
for x in range(len(search_list)):
if search_list[x] == target_value:
matches.append(x)
if matches:
return matches
else:
ra... |
244ebed8fc437f1891239178b04da5d27aecabf1 | terryfera/bbq-controller | /modules/db.py | 1,082 | 3.65625 | 4 | import sqlite3
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)
except Error as e:
print... |
f8f738fcbce1c28c81d681b40d9173ed9f6dc5a1 | OpenSO2/so2eval | /modules/strtodate.py | 555 | 4.0625 | 4 | # coding: utf-8
"""Parse a date from a string using a grouped regular expression."""
from __future__ import print_function
import datetime
import re
def strtodate(pattern, s):
"""Parse a date from a string using a grouped regular expression."""
regexp = re.compile(pattern)
r = re.match(regexp, s)
d = r.groupdict(... |
2c5d5e747e79dd8eb4866dda1f834b78265822ca | shhan0226/TensorFlow | /BasicDeepLearning/Lab3/Lab3-5.CostFunction_Gradient_optional.py | 1,132 | 3.5625 | 4 | # import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
X = [1, 2, 3]
Y = [1, 2, 3]
#W = tf.placeholder(tf.float32)
W = tf.Variable(5.) #말도 안되는 W의 값을 넣고 제대로 가는지 확인
# Our hypothesis for linear model X * W
hypothesis = X * W
#===> Manual Gradient #
gradient = tf.reduce_mean((W * X- Y) * ... |
95ccbb54c6f98a0fb5e0b912c932a61b84baeb06 | tpgmartin/CodeEval | /Python/easy/longest_word.py | 316 | 3.5625 | 4 | import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
longest = ''
longest_length = 0
words = test.strip().split()
for word in words:
word_length = len(word)
if word_length > longest_length:
longest = word
longest_length = word_length
print longest
test_cases.close() |
27f0076210871f5471f2c7abb2a38fb1f2351192 | bhavesh622/Sem6 | /Data Mining/numtestarr3.py | 216 | 3.515625 | 4 | # Checking if none of the elements are 0 in an array
import numpy
p= numpy.array([0,5,6,7])
print(p)
q= numpy.array([1,2,3,4])
print(q)
print(numpy.all(p))
print(numpy.all(q))
# [0 5 6 7]
# [1 2 3 4]
# False
# True |
6985fbb424941dc0c0736f334e4ab35fe944c74e | kurrier/pytest1 | /math2.py | 1,207 | 4.15625 | 4 | #!/usr/bin/python
print "Python Calculator\n"
nonum = "Error: no number"
firstnum = "What is the first number?"
secnum = "What is the second number?"
def division(n1,n2):
div = n1/n2
print "%d divided by %d is: %d" % (n1, n2, div)
return div
def multiply(n1,n2):
mult = n1 * n2
print "%d multiplied... |
7399c1b34a9114c519fae3a55c3769d011fb4228 | AprajitaChhawi/365DaysOfCode.FEBRUARY | /Day 13 remove consecutive characters.py | 581 | 3.703125 | 4 | #User function Template for python3
class Solution:
def removeConsecutiveCharacter(self, S):
n=len(S)
stack=''
for i in range(0,n):
if(len(stack)==0):
stack=stack+S[i]
if(stack[-1]!=S[i]):
stack=stack+S[i]
return stack
... |
4becfb6581ba3b22bc309202f316baa035c0d7d4 | AprajitaChhawi/365DaysOfCode.FEBRUARY | /Day 20 array implementation of queue.py | 1,247 | 3.828125 | 4 | #User function Template for python3
class MyQueue:
def __init__(self):
self.que=[]
self.rear=None
self.front=None
self.size=0
def push(self, x):
self.que.append(x)
if self.front==None:
self.front=self.rear=0
else:
self.rear=se... |
371b1fd39ab18e16ff8991ad99b652ab42910e41 | AprajitaChhawi/365DaysOfCode.FEBRUARY | /Day 9 count of camel case character.py | 447 | 3.828125 | 4 | #User function Template for python3
class Solution:
def countCamelCase (self,s):
count=0
for i in s:
if(i.isupper()):
count=count+1
return count
# your code here
#{
# Driver Code Starts
#Initial Template for Python 3
t = int (input ())
for tc in ran... |
e688eec8a6ff8a0499f4de875d1e45c48bb85e45 | AprajitaChhawi/365DaysOfCode.FEBRUARY | /Day 1 check if number is balanced.py | 514 | 3.71875 | 4 | #User function Template for python3
class Solution:
def balancedNumber(self, N):
k=[]
for i in N:
k.append(int(i))
mid=(len(N)//2)
if(sum(k[:mid])==sum(k[mid+1:])):
return True
else:
return False
# your code here
#{
# Driver Code Starts
#Initial Template for P... |
10e9fb421e64d1a003881369743a9cff39a57717 | AprajitaChhawi/365DaysOfCode.FEBRUARY | /Day 13 implement two stacks in an array.py | 1,785 | 3.65625 | 4 | #User function Template for python3
'''
Function Arguments :
@param : a (auxilary array),
top1 and top2 are declared as two tops of stack.
# initialized value of tops of the two stacks
top1 = -1
top2 = 101
@return : Accordingly.
'''
def pop1(a):
global top1
if(top1==-1):
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.