blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
51f87fd40317bcac53b9a1552740131520d816dd | joehal9000/Capacitance-calculator | /Capacitor.py | 684 | 3.546875 | 4 | from __future__ import division
def calculate(node):
ecap = -1
if type(node.cargo) is not node:
print(node)
ecap = node.cargo
node = node.next
while node:
if type(node.cargo) is int:
print(node)
ecap = add(node, ecap)
node = node.next
... |
654339762aa8a8c0391ffaf42733b0b88c8b7e12 | sunsaijie/turtle_navigate | /src/draw.py | 5,597 | 3.65625 | 4 | from turtle import Turtle, done, setup, screensize, register_shape, delay, update, tracer, speed
from typing import Tuple
import time
UPDATE_SPEED = 0.1
class BaseBlock:
"""基本block"""
color = "white"
id_ = 0
class GoldMine(BaseBlock):
color = "yellow"
id_ = 7
class Mine(BaseBlock):
color =... |
0e37384ab374125f5072b95f8d5b50a54228a6f4 | lynnoflynn/python_practice | /Python2_class/HW2_4331.py | 2,037 | 3.703125 | 4 | # 定义天山童姥类
class Tonglao:
# 定义属性血量,通过传入参数得到
def __int__(self, My_HP):
self.My_HP = My_HP
# 定义属性武力值,通过传入参数得到
def __int__(self,My_Power):
self.My_Power = My_Power
#定义see_people 方法
def see_people(self,name):
#如果传入”WYZ”(无崖子),则打印,“师弟!!!!”,如果传入“李秋水”,打印“呸,贱人”,如果传入“丁春秋”,打印“叛徒!我杀了你... |
52478f73dc521a296b9811769629a4cf03a3e81f | lynnoflynn/python_practice | /Python0823/test.py | 173 | 4.28125 | 4 | namelist = ['lili','tom','jerry']
print('Our name:{}, {}, and {}'.format(*namelist))
name = 'lili'
print(f"my name is {name}")
print(f"my name is {name.upper()}")
-------
|
378bece3c37d91cd0efede8c0c1e198417791e3f | krishnadhara/programs-venky | /programs/Fibonnic Series.py | 621 | 3.953125 | 4 | # n=int(input("enter your number: "))
# a=0
# b=1
# i=0
# if n<=0:
# print("enter positive number!!")
# elif n==1:
# print("the fibonnic series are",n)
# print(a)
# else:
# print("the fibonnic series upto",n)
# while i<=n:
# print(a,end=" ")
# nth = a + b
# a=b
# b=nt... |
6251f5356b05c94aff69129cd1fdfc87c2e59d4e | krishnadhara/programs-venky | /oops_concept/encapsulation/encapsul1.py | 405 | 3.9375 | 4 | class Encapsulation:
a = "hello"
_a = "python"
__a = "welcome"
def hello(self):
print("in hello method")
def welcome(self):
print("in welcome method")
def __abc(self):
print("in private method")
obj = Encapsulation()
#print(dir(obj))
print(obj.a)
print(obj._a)
#print(obj.... |
81c86a94615a36d1b9b8ce35e7fb558766ae98a8 | krishnadhara/programs-venky | /tutorial_prog/strings_py/count_repeated_wordinastr.py | 205 | 3.6875 | 4 | str = "the quick brown fox jumps over the lazy dog"
words = str.split()
print(words)
count = {}
for word in words:
if word in count:
count[word]+=1
else:
count[word]=1
print(count)
|
ca848467664ba3965182c0474922bd76467e61ce | krishnadhara/programs-venky | /tutorial_prog/dict_prog/dict_sum_values.py | 231 | 3.609375 | 4 | '''my_dict = {'data1':100,'data2':-54,'data3':247}
sum = 0
for k,v in my_dict.items():
sum+=v
print(sum)'''
my_dict = {'data1':100,'data2':-54,'data3':247}
lst =[]
for k,v in my_dict.items():
lst.append(v)
print(sum(lst))
|
25a83370a0803319cb7903ab4feaa9dc37614939 | krishnadhara/programs-venky | /generator_py/gen_powtwo.py | 143 | 3.734375 | 4 | def my_gen(max = 0):
n = 0
while n<max:
yield 2**n
n+=1
p = my_gen(10)
print(p)
it = iter(p)
for n in it:
print(n)
|
ffdb043138763172a80e0dca71f4f428a87ce882 | akash4102/turtle | /pattern.py | 529 | 3.71875 | 4 | import turtle
t=turtle.Turtle()
t.hideturtle()
t.speed(0)
def draw_circle(x,y,color,rad):
t.up()
t.goto(x,y)
t.down()
t.begin_fill()
t.circle(rad)
t.fillcolor(color)
t.end_fill()
draw_circle(0,0,"green",50)
draw_circle(200,200,"orange",50)
draw_circle(-200,200,"blue",50)
d... |
0c9992a6eb36b8d170a7936b9ca1341d9b18ee5d | RamyaRaj14/assignment2 | /discount calculator.py | 741 | 4.15625 | 4 | #discount calculator
purchase_amt=int(input("Enter the purchased amount"))
if purchase_amt>=100 and purchase_amt<=1000:
print("Discount is 0%")
discount=purchase_amt*0//100
total_bill=purchase_amt-discount
elif purchase_amt>=1001 and purchase_amt<2000:
print("Discount is 15%")
discount=purch... |
7ee73bf6b6af2a475c0630ba8d5076226451fd17 | shmargadt/mgr-tools | /trello/xlsx_importer.py | 2,412 | 3.59375 | 4 | import datetime
import xlsxwriter
def open_xlsx_file_and_return_workbook():
"""Create a workbook with current time name
Returns:
workbook (workbook): workbook object for writing excel files.
"""
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
output_file_name = "trello_status-{0}.xlsx".f... |
63345cc338631e1f12f1897a8e8059bd5d4eee2b | jzdsml/LintCode-contests | /Contest#030_Problem#0716_Add_and_Search.py | 448 | 3.75 | 4 | class Solution:
"""
@param inputs: an integer array
@param tests: an integer array
@return: return true if sum of two values in inputs are in tests.
"""
def addAndSearch(self, inputs, tests):
set_tests = set(tests)
N = len(inputs)
for i in range(N - 1):
for j ... |
a86a06dc383ac523e491ba4459e960b25c5b2bc2 | jRead2k18/UserOOP_Chained | /userOOP_chained.py | 1,242 | 3.578125 | 4 | class User:
def __init__(self, username, email_address):
self.name = username
self.email = email_address
self.account_balance = 0
def make_deposit (self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.accou... |
63f7c24c6913aaa0bb19bd97722bbb205373208a | adityavyasbme/GetSetHedge | /src/pages/about.py | 11,590 | 3.90625 | 4 | import streamlit as st
def question(que):
st.markdown(f"<h3>{que}</h3>", unsafe_allow_html=True)
def answer(ans):
st.markdown(f"<p> {ans} </p>", unsafe_allow_html=True),
def add_source(link, title):
st.markdown(f"<a href='{link}'>{title}</a>", unsafe_allow_html=True)
# pylint: disable=line-too-long
... |
3c8dedd5289adae2c3ce648ce02d1f0c59c059ab | adityavyasbme/GetSetHedge | /src/eda/graphs.py | 1,749 | 3.875 | 4 | # Has a class to plot a graph
import altair as alt
import streamlit as st
import pandas as pd
class Graph():
"""Class to plot graphs
"""
def plot_multiple_tickers(self, parent):
"""Function to plot multiple columns into single graph using altair lib
Args:
parent (object): Pare... |
67fdfe194762b3733c4ce654542ab0ef1cc94684 | rishabh6398/DataStructureAlgorithm | /LL2 assignment.py | 923 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
class Node:
def __init__(self,val):
self.data = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self,data):
newNode = Node(data)
if self.head == None:
self.head = newN... |
0274d912bdd64bfd7d0c05359fea30343d30e4be | nikki-t/minus80 | /minus80_main.py | 680 | 3.734375 | 4 | """Program that monitors a Raspberry Pi attached to a minus 80 freezer.
Functions
---------
monitor(): Creates Board object to watch the state of an input pin.
"""
# Local application imports
from app.Board import Board
PIN = 11
def monitor():
"""Creates a Board object to monitor the state of an input pin."... |
3a79a8b706248971d73f0d825adb68b43b9ead0b | kassenq/transform | /PigLatin.py | 3,303 | 3.953125 | 4 | '''
Created on Oct 15, 2018
@author: kassen qian
'''
'''
def encrypt(w):
'''
#this function turns string w into the pig latin version of the string.
'''
if w[0] == "a" or w[0] == "e" or w[0] == "i" or w[0] == "o" or w[0] == "u":
return w + "-way"
elif w[0] == "A" or w[0] == "E" or w[0] == "... |
e2743fef2adf86411bb09abe663cf754d2c3c100 | lalitbhadana/spy-chat | /spy/spy_friend.py | 731 | 3.90625 | 4 | import validation
friends = []
new_spy_profile = {
'new_spy_name' : " ",
'new_spy_salutation' : " ",
'new_spy_age' : 0,
'new_spy_rating' : 0.0,
'chat' : []
}
def add_friend():
print(" U want to update new profile")
new_spy_profile['new_spy_name']=input("Enter a name")
new_spy_profile['new_spy_salutati... |
10cac350b0e31340c8352db9c2dcf1b7188bb049 | dqi/ctf_writeup | /2015/tmctf/crypto200/decrypt.py | 1,987 | 3.75 | 4 | #!/usr/bin/python
from Crypto.Cipher import AES
import binascii
import string
import itertools
# given
bKEY = "5d6I9pfR7C1JQt"
# use null bytes to minimize effect on output
IV = "\x00"*16
def encrypt(message, passphrase):
aes = AES.new(passphrase, AES.MODE_CBC, IV)
return aes.encrypt(message)
def decrypt... |
1ceb58db4cb802c647ba28a5ef2dfa6c6ea84f3c | ChenAa110/bringing_it_all_together | /dierbufen/13/a.py | 1,779 | 4.125 | 4 | class Rectangle():
def __init__(self, width, length):
self.width = width
self.length = length
def calculate_perimeter(self):
return self.width * 2 + self.length * 2
class Square():
def __init__(self, s1):
self.s1 = s1
def calculate_perimeter(self):
return self... |
7e899ca4cfa5ea86441bf0220dae3d02f089f3f3 | ChenAa110/bringing_it_all_together | /zha/a-9-3.py | 399 | 3.609375 | 4 | class Animal:
def speak(self):
print('动物叫,但不知道是什么动物')
class Dog(Animal):
def speak(self):
print('狗叫:旺旺的叫')
class Cat(Animal):
def speak(self):
print('猫叫:喵喵的叫')
class Car:
def speak(self):
print('dududu')
def start(obj):
obj.speak()
start(Car())
an1=Dog()
an2=Cat(... |
df1b2f89e046508ed33ce2836f7900d47f01a4f3 | ChenAa110/bringing_it_all_together | /zha/a-9-1.py | 1,269 | 3.90625 | 4 | class Account:
__interest_rate=0.0568
def __init__(self,owner,amount):
self.owner=owner
self.__amount=amount
def __get_info(self):
return "{0}金钱:{1}利率:{2}".format(self.owner,self.__amount,Account.__interest_rate)
def desc(self):
print(self.__get_info())
account=Accoun... |
62f458259df49e2b3ea124fb4c06c4bf527a331e | ChenAa110/bringing_it_all_together | /diyibufen/4/a.py | 297 | 3.859375 | 4 | x = 1
y = 2
z = 3
def f():
x = 4
y = 5
z = 6
print(x)
print(y)
print(z)
print(x)
f()
try:
a = input("type a number:")
b = input("type another:")
a = int(a)
b = int(b)
print(a / b)
except (ZeroDivisionError, ValueError):
print("Invalid input.")
|
5d22927a905129283ba53c9a34b7a4da9c3e101e | ChenAa110/bringing_it_all_together | /disibufen/22/a.py | 249 | 3.578125 | 4 | class Solution(object):
def runningSum(self, nums):
if not nums:
return []
for i in range(1, len(nums)):
nums[i] = nums[i] + nums[i - 1]
return nums
nums=[1,2,3,4,5,]
s=Solution()
s.runningSum() |
2eee8ef668bdf3ee61fbfcc483ef6981550b29ee | ninjutsoo/Quoridor-Battleship | /Battleship.py | 7,234 | 3.9375 | 4 | import copy
import os
def start_battleship():
global boardsize, numbers, alphabet
player1_name = input("What is the name of Player One ? ")
player2_name = input("What is the name of Player Two ? ")
boardsize = int(input("Size of board : "))
turn_number = int(input("Number of Turn : "))
... |
cb609f5e0244bbb3b9ec62c919bdc17ab41ddb82 | sleticalboy/Pylearn | /com/sleticalboy/python/basic/06_list_operate.py | 1,092 | 4.15625 | 4 | #! /usr/bin/env python
# -*- encoding=utf-8 -*-
languages = ['python', 'java', 'c#', 'php', 'go', 'perl']
# 循环遍历列表元素
for item in languages:
print(item.title() + ', a well-known language.')
print("\tI can't wait to learn it.")
print('There are all language I know.')
for value in range(1, 11):
print(value)... |
b650ce4013de91d79facad59d9291c9186455a80 | sleticalboy/Pylearn | /com/sleticalboy/python/basic/04_number.py | 462 | 3.875 | 4 | #! /usr/bin/env python
# -*- encoding=utf-8 -*-
num = 2 + 3
print(num)
num = 2 * 3
print(num)
num = 2 / 3
print(num) # 0.6666666666666666
num = 2 - 3
print(num) # -1
num = 2 ** 3
print(num) # 8
num = 2 ** (3 + 3)
print(num) # 64
num = (2 + 3) ** 3
print(num) # 125
num = 0.1 + 0.2
print(num) # 0.3000000000... |
55e0c53e37eb51c5d21e16105a7c3afa060ed2df | sleticalboy/Pylearn | /com/sleticalboy/data_analysis/produce/mpl_squares.py | 531 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
# 绘制折线图
# 生成列表
values = list(range(1, 101))
squares = [value ** 2 for value in values]
# print(squares)
# 设置曲线粗细
plt.plot(values, squares, linewidth=2)
# 设置标题并给坐标轴加上标签以及字体大小
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fonts... |
b9155082821b262e79167c145f214fff142d9a6e | khpandya/CTCI | /chapter_02/p05_sum_lists.py | 4,817 | 3.734375 | 4 | from linked_list import LinkedList
from LL import MyLL
from LL import Node
def makeEqual(l1, l2):
curr1=l1.head
curr2=l2.head
while curr1.nxt!=None and curr2.nxt!=None:
curr1=curr1.nxt
curr2=curr2.nxt
if curr1.nxt==None and curr2.nxt==None:
return True
elif curr1.nxt==None:
... |
20d6414006e9484c2bc84dd6c8ef094d722d2b2a | Rogety/LabelGenerator | /scripts/convert2htslabel.py | 58,349 | 4.0625 | 4 | import os
import re
def list_shift(listP , direction , count , _type_):
'''
if direction == "right":
if count == 1:
listP.pop(-1) ##pop() : 預設是刪掉最後一個
listP.insert(0 , '0' )
elif count == 2:
listP.pop(-1)
listP.pop(-1)
lis... |
91aa008f3bb2420076f6e8d7c4f65a041d499b2a | Adiyasa271101/Hebbian-JST--python | /hebbian.py | 3,638 | 3.5625 | 4 | #Membuat inputan banyak data dan X
n = int(input("Input banyak data = " ))
xn = int(input("Input banyak X = "))
#inisialisasi bobot, bias, dan dw (Menginisialisasi nilai bobot,bias, dw nol, dimana bobot mengikuti banyak X sehingga menggunakan perulangan)
w = []
dw = []
for i in range(xn):
w.append(0)
... |
7897e6bb7202d595b4fbfaaddaa2a8c5364fc3dd | HipyCas/Utilities-Lib-Python | /utilities/geometry.py | 3,487 | 3.5 | 4 | """
This is a geometry module that adds classes and functions in the field of geometry, including coordinates, planes, etc.
"""
class Plane:
"""
Geometry plane to store, create and handle shapes, coordinates and all geometry elements
"""
all_coordinates = []
all_shapes = []
def __init__(self,... |
d577b2a7267966f03775af3da276fc92a42bf04a | HipyCas/Utilities-Lib-Python | /utilities/maths/equations.py | 983 | 3.859375 | 4 | from math import sqrt
from utilities.maths import Number
def solve_second_degree(a, b, c):
if type(a) == tuple or type(a) == list:
a = a[0]
if type(a) == str:
try:
a = int(a)
except ValueError:
return None
elif type(a) != int and type(a) != float and type(a... |
bec8f12cfac96b6d507b264fe75ad0bb9e1ce9c1 | jacobturjeman/turtle_crossing_game | /scoreboard.py | 914 | 4.03125 | 4 | from turtle import Turtle
FONT = ("Courier", 24, "normal")
# creating a separate class for the scoreboard
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.goto(-180, 260)
self.hideturtle()
self.score = 0
self.write(f"Score: {self.s... |
abd48e61cf65306bf349454c87c67232f111b4c9 | Awannaphasch2016/AdaptiveGraphStructureEmbedding | /Examples/PythonBasic/inherit.py | 458 | 3.734375 | 4 | class First(object):
def __init__(self):
print("first")
# class Second(First):
class Second():
def __init__(self):
print("second")
# class Third(First):
class Third():
def __init__(self):
print("third")
# class Fourth(Second, Third):
class Fourth(Third, Second):
def __init__(s... |
294c108feba6197f33cbe6405b673e179ed08037 | deep-sarkar/python_programming | /logical/leap_year.py | 470 | 3.9375 | 4 | '''
input : year
returns : true if leap year else false
'''
def isLeapYear(year):
try:
if year < 0:
return "Enter a valid year"
elif year % 400 == 0 or year % 4 == 0 and year%100 != 0:
return True
return False
except TypeError:
return "Enter a numerical v... |
6ab1a222e0cb80df0e85ba58b08049aa03daabdc | deep-sarkar/python_programming | /logical/gambler.py | 1,047 | 3.78125 | 4 | import random
class Gambler:
def gamble(self, stack, goal, no_of_bet):
win = 0
loss = 0
total_try = 0
while no_of_bet != 0:
if stack == goal:
print("you won the game. Total try :", total_try)
break
toss = random.r... |
e444631303fa34773578f202c06988a15eb45fd8 | SemihDurmus/Python_Helper | /2_Codes/Assignment_14_Fizz_Buzz.py | 591 | 4.25 | 4 |
# Assignment_14_Fizz_Buzz
"""
Print numbers from 1 to 100 inclusively following these instructions:
if a number is multiple of 3, print "Fizz" instead of this number,
if a number is multiple of 5, print "Buzz" instead of this number,
for numbers that are multiples of both 3 and 5, print "FizzBuzz",
print the rest of t... |
716dd86c5dcdd08ea5e03e22124f499cec388c35 | SemihDurmus/Python_Helper | /2_Codes/Assignment_8_Most_Frequent_Element.py | 687 | 4.59375 | 5 | # Assignment_8_Most_Frequent_Element
"""
Task : Find out the most frequent number and its frequency.
Write a program that;
Finds out the most frequent number in the given list. Calculates its frequency. Prints out the result such as :
Example
Given list: numbers = [1, 3, 7, 4, 3, 0, 3, 6, 3]
Desired Output: the m... |
bb886be381d89ee0905b5d7628113dce0f4cd26b | SemihDurmus/Python_Helper | /2_Codes/Assignment_1_Weekly_Profit.py | 1,063 | 4.03125 | 4 | #Assignment_1_Weekly_Profit
# If you had deposited a coin on the cryptocurrency exchange
#that brought 7% fixed profit daily for a week,
#how much would your $ 1000 reach at the end of the 7th day?
deposit = 1000
profit = 0.07
print("You have $", deposit, "as initial deposit\nThe profit ratio is: ", int(profit*1... |
1e98ce2a14f2796fdad420ecd1679135e1cb0660 | adityashah05/flaskapi | /test/test_flaskapi.py | 2,199 | 3.703125 | 4 | """
This is the test module of the flaskapi.py, the test cases check the following:
1) The API is returning expected data for a valid request
2) The API is returning expected data for a invalid valid request, eg http://localhost:5000/xxxx
3) The API is returning expected data for a date for which there is no data, http... |
ac16ba38aba525ecd747eb7e9bcd2b3fad45f0a9 | ivanovs85/python_basic | /Module17/03_random_competition/main.py | 355 | 3.53125 | 4 | import random
first_team = [round(random.uniform(5, 10), 2) for _ in range(20)]
second_team = [round(random.uniform(5, 10), 2) for _ in range(20)]
winners = [max(first_team[unit], second_team[unit]) for unit in range(20)]
print('Первая команда:', first_team, '\nВторая команда', second_team, '\nПобедители', winners)
|
34f1af34cba02b67542bd530a419c50839891de3 | ivanovs85/python_basic | /Module15/03_cells/main.py | 423 | 3.78125 | 4 | cell = int(input('Введите количество клеток: '))
unsuitable_list = []
for rank in range(1, cell + 1):
print('Эффективность', rank, 'клетки: ', end='')
efficiency = int(input())
if efficiency < rank:
unsuitable_list.append(efficiency)
print('Неподходящие значения: ', end='')
for i in unsuitable_li... |
46f00cd04375f560a19ee60cde9b00f33963545b | ivanovs85/python_basic | /Module16/01_scary_code/main.py | 525 | 3.8125 | 4 | main_list = [1, 5, 3]
list_a = [1, 5, 1, 5]
list_b = [1, 3, 1, 5, 3, 3]
main_list.extend(list_a)
count_a = 0
count_b = 0
for elm in main_list:
if elm == 5:
count_a += 1
main_list.remove(elm)
main_list.extend(list_b)
for elm in main_list:
if elm == 3:
count_b += 1
print('Кол-во цифр 5... |
9526209351ba4e728583a4d451ef132942bf9437 | ivanovs85/python_basic | /Module14/04_reverse_num/main.py | 690 | 3.90625 | 4 | first_num = input('Введите первое число: ')
second_num = input('Введите второе число: ')
def revers(num):
revers_num = ''
revers_int = ''
for i in num:
if i == '.':
revers_int = revers_num + '.'
revers_num = ''
continue
revers_num = i + revers_num
re... |
24f09213b868030a4587db29201c937cf7ba9610 | Aksid83/crckng_cdng_ntrvw | /zero_matrix.py | 1,172 | 4.03125 | 4 | """
Write an algorithm such that if an element in an MxN matrix is 0,
its entire row and column are set to 0.
"""
def set_zeroes(matrix):
row = [False for r in range(len(matrix))]
column = [False for c in range(len(matrix[0]))]
print('Initial matrix:')
for el in matrix:
print(el)
print('\n... |
91c8ce67b43541cb1591497e8f82ee228169c856 | khushi3030/Master-PyAlgo | /Topic Wise Questions with Solutions/Linked List/reverse_of_LL_iterative.py | 1,723 | 4.46875 | 4 | """ The Program is to reverse a linked List using iteration """
class Node: #creating a node
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class linkedlist: #creating a linked list
... |
1cf4e63eee11e568312f3de8c2066d4573d0a18d | khushi3030/Master-PyAlgo | /Data Structures/Double_ended_queue.py | 3,090 | 4.34375 | 4 | """ This program is written to execute operations of double ended queue until the programer requires"""
print("**DOUBLE ENDED QUEUE**")
class Deque: #creating a class for deque
def __init__(self):
self.items = []
def isempty(self): #intially qu... |
cfe715326a88fad335f791a94a8d435f7db45875 | khushi3030/Master-PyAlgo | /Algebra/Happy_Number.py | 1,360 | 4.34375 | 4 | '''
Starting with any positive integer, replace the number with the sum of the squares of its digits.
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle
which does not include 1. Those numbers for which this process ends in 1 are happy number.
'''
'''
Ha... |
753c44bd1363f34d04964f49086aceb4f919be6b | khushi3030/Master-PyAlgo | /Topic Wise Questions with Solutions/Array/Get_Max.py | 3,067 | 3.9375 | 4 | """
Query : Get Max
Task:
Given two vectors A and B of length a and b respectively and an integer N .
We have to make a maximum number of length N from the integers given in the two vectors A and B
such that the relative order of the digits from the same vector should be retained
Output a string of the obtained maximu... |
79cf92e0433213dc05e6f7c4a5ff71004cb98db4 | khushi3030/Master-PyAlgo | /Algebra/Table_of_a_Number.py | 797 | 4.375 | 4 | '''
Aim: The aim is to print the first 10 multiples of the number entered.
'''
# getting the input
n = int(input().strip())
# looping from 1 to 11 because we want first 10 multiples only
for i in range(1,11):
# printing the table for the number
print(str(n) + ' x ' + str(i) + ' = '... |
7fe4082bdf3b24dfc9f2860042efc04ea1a481cf | khushi3030/Master-PyAlgo | /String/one_away.py | 2,187 | 4.15625 | 4 | """ This program is written to check if a String can be modified into another String by only one single operation that can be
1. replacement
2. delete
3. insert
"""
def is_Edit_Distance_One(string_1, string_2): #Defination of the function
String_1_length = len(string_1) ... |
f23924517d9a4689a18e8dae83f00e82a6eb8e9b | khushi3030/Master-PyAlgo | /Algebra/Valid_Powers.py | 1,252 | 4.25 | 4 | '''
Aim: Given two integers n and p, the goal is to output n^p if and only if n
and p both are positive integers, else, print 'n and p should be non-negative'.
'''
# class to compute the valid results
class Calculator:
def power(self,n,p):
if n>=0 and p>=0:
return(n**p)
els... |
b9bf7e47f8205a664eaf7c8cb97ee18317d63a28 | iclare/wayfinder | /src/pipeline/util.py | 1,954 | 3.546875 | 4 |
from geopy import distance as gpdistance
def row_in_region(row, region):
"""Return whether the coordinates of this row is within the rectangular region.
:param row: Pandas DataFrame row with coordinate lon and lat.
:param region: Rectangular area to check.
:return: True or False
"""
# coord[... |
d8e36a09b255ace750906fe8d953969c0e6d9dc3 | Vl-tb/Json_navigation | /json_navi.py | 8,579 | 3.953125 | 4 | """
This module contains functions, which
help user to navigate and search data in
.json file.
"""
import blessed
import json
import pprint
def read_json(path: str) -> object:
"""
This function reads a .json file and returns
python objects(dict, str, etc).
"""
if path[-5:] != ".json":
re... |
ee3d9f033c20277fa1acf6202277e98c807c141a | Pd1589/rock-paper-scissors-excercise | /game.py | 1,167 | 4.15625 | 4 | # game.py
import random
print("Rock, Paper, Scissors, Shoot!")
user_choice = input("Please choose one of: 'Rock' ,'Paper' ,'Scissors' --->")
print("USER CHOICE: ", user_choice)
#EXIT IF INVALID ENTRY
if (user_choice == "Rock") or (user_choice == "Paper")or (user_choice == "Scissors"):
print("VALID ENTRY KEEP GOING... |
04357af45e08b7314437a28f9eb1a8f720e6434f | jlrobbins/class-work | /backle.py | 119 | 3.71875 | 4 | dinner = 'ramen'
index = len(dinner)-1
while index >= 0:
lett = dinner[index]
print(lett)
index = index - 1 |
5790329ebae8a9e1d1142e6be403146be13ec9ac | jlrobbins/class-work | /theprogramcount.py | 296 | 3.578125 | 4 | fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
# print 'Debug:', words
if len(words) == 0 : continue
if words[0] != 'From' : continue
count = count + 1
print(words[1])
print("There were",count,"lines that started with From in this file.") |
a9d86961025c94c71ee9ef4ea43bfcfe753e7266 | jlrobbins/class-work | /alphabetcount.py | 522 | 3.515625 | 4 | fname = input("Enter a file name: ")
try:
fhand = open(fname)
except:
print("Sorry, that file doesn't exist.")
exit()
letcoun = dict()
for line in fhand:
line = line.lower()
for c in line:
if c not in 'abcdefghijklmnopqrstuvwxyz' : continue
if c not in letcoun:
letcoun[c]... |
80a36a569dccc6381a7cdf83f79affd1e6000006 | IL-two/Python | /control_of_funds/Script/Product_list.py | 1,589 | 3.875 | 4 | from Script.Product import Product
# Создание листа объектов
class ProductList(list):
def __init__(self):
self.__listProduct = list()
def addProduct(self, product):
self.__listProduct.append(product)
# product = Product()
# self.__listProduct.append(product.addProdu... |
b9bb05c53ade4427ee5b21fcecc89e5b01337a26 | panzarino/project-euler | /project5.py | 140 | 3.828125 | 4 | def gcf(x,y):
return y and gcf(y, x%y) or x
def lcm(x,y):
return x*y/gcf(x,y)
n = 1
for x in range(1,21):
n=lcm(n,x)
print (n)
|
571a0291531a0ea6129a03bc93c2cc6e6a68da57 | human02/daily-coding-problem | /1.py | 596 | 4.0625 | 4 | """
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array
is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24]. If our... |
9aa98bc69da463d88b4a412e55442207ae80f968 | harsh81717/guvi | /set2/12.py | 125 | 3.65625 | 4 | n=input()
if n.isdigit()==True and n==n[::-1]:
print("yes")
elif n.isdigit()==True:
print("No")
else:
print("invalid")
|
92c745a6b94a5188e76b8ea35332f64beb867aac | harsh81717/guvi | /set1/8.py | 103 | 3.6875 | 4 | n=input("Enter a number")
try:
n=int(n)
sum=(n*(n+1))//2
print(sum)
except:
print("invalid")
|
6fed6a43dec483f6a168850919f94b904dcd2dbf | yudumerg/Prediction-of-currency-exchange-rate- | /estimatingDollarPrice.py | 892 | 4.0625 | 4 | # Adding the libraries for project
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading the data set
data = pd.read_csv('2016dolar.csv')
print(data)
date = data[['Date']]
print(date)
price = data[['Price']]
print(price)
#Dividing the data set as train and test data
from skle... |
a91d332eb7e3084a37b3ae7433a9d0cc27e27447 | marcelofabiangutierrez88/cursoPython | /ejercicio14_InvertirNumeros.py | 325 | 4.125 | 4 | #Dado un número de dos cifras, diseñe un algoritmo que permita obtener el número invertido. Ejemplo, si se introduce 23 que muestre 32.
def invierte():
num=int(input("Ingrese numero de dos cifras:" ))
numConvert=str(num)
print("Su numero invertido es: ",numConvert[::-1])
def main():
invierte()
main... |
ff2aecd836c73ed764290ea9e9f17ac2833377ca | marcelofabiangutierrez88/cursoPython | /Listas/Ejercicio2_ListaStringInvertida.py | 479 | 4.34375 | 4 | #Ejercicio 2
#Crea una lista e inicializala con 5 cadenas de caracteres
#leídas por teclado.
#Copia los elementos de la lista en otra lista
#pero en orden inverso, y
#muestra sus elementos por la pantalla.
def lista():
lista = []
for i in range (5):
x = input("Ingrese cadena a la lista :")
lis... |
e973701c81b8817076e5b46535f27df336ad1d20 | marcelofabiangutierrez88/cursoPython | /EstructurasRepetitivas/Ejercicio4_CompruebaNums.py | 688 | 3.984375 | 4 | #Ejercicio 4
#Realizar un algoritmo que pida números
#(se pedirá por teclado la cantidad de números a introducir).
#El programa debe informar de cuantos números introducidos son mayores
#que 0, menores que 0 e iguales a 0.
def pideNumeros():
x = int(input("Ingrese cantidad de numeros: "))
i=0
conMenor=0
... |
51aa883cb3e168188c3950e3d49bf5e4515f0b00 | marcelofabiangutierrez88/cursoPython | /EstructuraIF/Ejercicio5_ValidaUserPass.py | 474 | 3.71875 | 4 | #scribe un programa que pida un nombre de usuario y una contraseña y si se ha introducido “pepe” y “asdasd” se indica “Has entrado al sistema”, sino se da un error.
def userPass():
user = input("Ingrese usuario: ")
password = input("Ingrese password: ")
if user == "pepe" and password =="asdasd":
... |
ad19a86e86fc3819c2fbd036851dd88f452460bf | marcelofabiangutierrez88/cursoPython | /EstructurasRepetitivas/ejercicio9_Potenciacion.py | 391 | 4.1875 | 4 | #Ejercicio 9
#Escribe un programa que dados dos números, uno real (base) y
#un entero positivo (exponente), saque por pantalla el resultado de la potencia. No se puede utilizar el operador de potencia.
def potencia():
x = float(input("Ingrese base: "))
y = int(input("Ingrese exponente: "))
pot = x ** y... |
83927b409acd1f354afe13d978c5987cd3db01b9 | marcelofabiangutierrez88/cursoPython | /ejercicio3_calculaHipotenusa.py | 324 | 3.953125 | 4 | # Dados los catetos de un triángulo rectángulo, calcular su hipotenusa.
import math
def hipotenusa():
lado = int(input("Ingrese primer cateto: "))
lado1 = int(input("Ingrese segundo cateto: "))
hipo = lado**2+lado1**2
tenusa=math.sqrt(hipo)
print(tenusa)
def main():
hipotenusa()
main... |
db4e4af6b7deddd328c346a72cf6ddb3c1fb175d | marcelofabiangutierrez88/cursoPython | /Listas/Ejercicio1_ListaAleatorios.py | 570 | 4.15625 | 4 | #Ejercicio 1
#
#Realizar un programa que inicialice una lista con 10 valores
#aleatorios (del 1 al 10) y posteriormente muestre en pantalla
#cada elemento de la lista junto con su cuadrado y su cubo.
import random
def lista():
lista = []
for i in range (10):
lista.append(random.randint(1,100))
... |
529fd92affcf7cc4b5d212aedd20a85757934aea | mydapp/learnning | /builder.py | 1,013 | 3.625 | 4 | from abc import ABCMeta,abstractmethod
class Builder():
__metaclass__= ABCMeta
@abstractmethod
def draw_arm(self):
pass
@abstractmethod
def draw_leg(self):
pass
@abstractmethod
def draw_head(self):
pass
class Thin(Builder):
def draw_arm(self):
print(... |
92b5cd9bc04ea66e841641715dca07a6b86904e3 | Glorwynn/shadows_empire | /Organisation.py | 3,200 | 3.84375 | 4 | from random import *
class Organisation:
"""
Class for Organisation
======================
Parameters :
------------
- name: String
- chief: Character
- members: List of Character
- description: String
"""
def __init__(self,... |
96537c5cf409d9d4b8c8083dec6fcab8d623630b | gaylonalfano/python-statistical-analysis-course | /section-2-exploring-data-analysis/prepare_dataset.py | 2,180 | 3.625 | 4 | #%% [markdown]
### Preparing a dataset
#%%
import pandas as pd
import numpy as np
df = pd.read_csv(
"/Users/gaylonalfano/Code/python-statistical-analysis-course/section-2-exploring-data-analysis/Diabetes.csv"
)
df.info()
#%%
df.head()
#%% [markdown]
### `df.fillna(0)` returns a df with all nulls replaced with ... |
38557f9fee1ef936bb3e0935e82d84590193835b | yongxuUSTC/cracking_code_interview_v6 | /8.6_TowersOfHanoi.py | 3,229 | 3.703125 | 4 | ### CCI6 8.6 Towers of Hanoi
import sys
# first, we should construct a multi-stack class
class MultiStack(object):
def __init__(self, total_stacknum, stacksize):
self.total_stacknum=total_stacknum # how many stacks
self.stacksize=stacksize # size for each stack, all the same size
self.arr... |
88cd14847aad020173dc20a6a78509685f9a56f2 | yongxuUSTC/cracking_code_interview_v6 | /8.9_pairsOfParentheses.py | 905 | 4.0625 | 4 | ###CCI6 8.9 n paris of balanced parentheses
def paranthesis(output = "", open = 0, close = 0, n = 1):
if open == n and close == n:
print "final output:", output , ',' #base case to stop
else: # the common condition for the recursion, so it should use else for difference
print "output1", output ... |
6d3f6e6e9c0bf4c5a18a527c44051d0f280c3556 | guti7/DifficultPython | /ex17.py | 896 | 3.828125 | 4 | # Exercise 17: More files
# Copy one file to another.
from sys import argv
# exists returns true if a file exists, based on its name in a string
from os.path import exists
script, from_file, to_file = argv
# print "Copying from %s to %s" % (from_file, to_file)
#
# # We could do these on one line
# # in_file = open(f... |
f6c61e9458fe5b359853eca497b1c0d2953b8f72 | junzecao/ProjectEuler | /014.py | 997 | 3.59375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
length_history = [0] * 5000001
number_stack = []
length_stack = []
def populate_length(n):
if n == 1:
return 0
if n < 5000001 and length_history[n] != 0:
return length_history[n]
if n%2 == 0:
length = populate_le... |
cfcca377fdd71160c69fafce0d8c86428857866a | junzecao/ProjectEuler | /009.py | 547 | 4.09375 | 4 | #!/bin/python
import sys
import math
def rounding(n):
if abs(round(n)-n) < 0.0001:
return int(round(n))
return 0
def Pythagorean_triple(n):
if n%2 or n<12:
return -1
start = int(math.ceil(max(n/3+1,n*(math.sqrt(2)-1))))
for c in xrange(start,n/2):
a = rounding((float... |
348b53b4d7c786e91a57be7c7093e2a4a3f95cd9 | Raenllanthos/week4 | /day1/whiteboard.py | 495 | 4.1875 | 4 | # Create a function that given a string as a parameter of upper/lower case letters
# and empty space characters (" "), return the length of the last word.
# Meaning, the word that appears far most to the right if we loop through the words.
# Example Input: "Hello World"
# Example Output: 5
def famousLastWord(s):
... |
d4b3dd242b9264ccea7e69b023fd1885a687f982 | critipan/PythonGUI | /src/Button窗口部件.py | 1,578 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 10:24:04 2019
练习使用Button
@author: G
"""
#导入库
import tkinter as tk
import time,threading
#实例化窗口
window = tk.Tk()
#为窗口命名
window.title('练习使用Button')
#设置窗口大小
window.geometry('500x300')
#在窗口上添加标签
var = tk.StringVar()#将Label标签的内容设置为字符类型,用Var来接受hit_me传出的内容用以显示在标签上
l = tk.Lab... |
887549ece88a448b2cff1bbf83dc68b7a7c61e1a | MarinaMirge/pythonhomework | /HomeWork 4.1.py | 2,903 | 4.21875 | 4 | class flight:
__destination = ' '
__flight_number = ' '
__airplane = ' '
__departure_time = ' '
__day = ' '
def __init__(self, destination0, flight_number0, airplane0, departure_time0, day0):
self.__destination = destination0
self.__flight_number = flight_number0
... |
52bee58f20a311fa748c289b03c438bebbfd3192 | NitishKumar0297/python-programs | /tuple.py | 95 | 3.515625 | 4 | tpl=(1,2,3,-5,-7,'india','england','vijay','marray')
print(tpl)
print(tpl[0:3])
print(tpl[-5]) |
119a8d0b8878a57c4639acc9a17df96827d734f9 | divya-kustagi/python-stanford-cip | /examples/bluescreening.py | 1,215 | 4 | 4 | """
File: bluescreening.py
--------------------
This program adds the foreground to the background image,
but only copies over the pixels that are not too blue.
Concepts showcased:
Handling images in Python
"""
from simpleimage import SimpleImage
BRIGHTNESS_THRESHOLD = 153
def bluescreen(background, foreground):
... |
ffc8210bb2ddcb6bc04f94490dcdb0dbeefd0485 | divya-kustagi/python-stanford-cip | /assignments/assignment3/warhol_filter.py | 2,052 | 4.125 | 4 | """
warhol_filter.py
This program generates the Warhol effect based on the original image.
It creates an image which has the patch copied 6 times (in 2 rows and 3 columns) where each
patch gets recolored.
"""
from simpleimage import SimpleImage
import random
N_ROWS = 4
N_COLS = 6
PATCH_SIZE = 222
WIDTH = N_COLS * PA... |
2bff431370ccc7783bd620a98abe701b5fe0217e | divya-kustagi/python-stanford-cip | /final_project/2player_Snake_Game.py | 14,391 | 4.03125 | 4 | """
2 player Snake Game: (By Divya Kustagi)
Welcome to the ‘Snake World’! This is my twist on a classic ‘Snake Game’.
About the Game:
This is a two-player version of the Snake Game Classic.
• Game starts with a prompt ‘Welcome to the Snake World! Your game begins in 3..2..1..’
• Each player has Keyboard controls prov... |
600a2cd60acab154a81f66bf602da14e4c41b39d | ddl-hust/PythonRobotis | /PathPlanning/RRT/rrt.py | 6,358 | 3.734375 | 4 | """
Path planning Sample Code with Randomized Rapidly-Exploring Random Trees (RRT)
author: AtsushiSakai(@Atsushi_twi)
"""
import math
import random
from IPython import embed
import matplotlib.pyplot as plt
show_animation = True
class RRT:
"""
Class for RRT planning
"""
class Node:
"""
... |
59656633b6c649d101d43b6a5416fc60f62ff482 | yasht01/lhd-encrypt-a-password | /transpose.py | 1,042 | 3.8125 | 4 | def rail_cipher(plaintxt):
step = (4, 2)
num_steps = 0
ciphertxt = ""
checked = [False for i in range(len(plaintxt))]
i = 0
while(not_all_checked(checked)):
while i < len(plaintxt):
if not(checked[i]):
ciphertxt += plaintxt[i]
checked[i] = ... |
ea54a6df5d156d9ff06aa706a29bffe0456fe5cf | AdrianPratama/AdrianSuharto_ITP2017_Exercise5 | /Exercise5-9.py | 212 | 4 | 4 | def generator(n):
while n >= 0:
yield n
n -= 1
finalcountdown = generator(int(input("Please input the first number here:")))
for x in finalcountdown:
print(x)
print(type(finalcountdown))
|
bf1442205f17c98f6943ad84b9f209a875079dac | HussainAther/scrape | /src/callback.py | 1,718 | 3.5625 | 4 | import csv
import re
from download import crawllink
"""
This callback class and function scrapes the country data
and saves it in a readable csv format. The callback lets you
handle multiple websites by using the function after certain events
(such as after the webpages of interest have been downloaded).
In this cas... |
27142de305ed9aac165a0fa1967e896643bb5251 | RPerron91/tip-calculator | /tip_calculator.py | 2,290 | 4.28125 | 4 | #Recursive function to get bill with valid type
def getBill():
#Set bill equal to user input
Bill = input("Enter Bill Total: ")
#Exception handling and converting Bill from string to float
try:
#Change input to float and return Bill with no whitespace
Bill = float(f"{Bill}\n")
#C... |
8ffffb44c552d0ffb4c7b11e4c397d2ceb0894f2 | bpurinton/fault-swath | /LSDPlottingTools/locationmap.py | 4,599 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Location map.
Plots a location map using the Cartopy package
Install cartopy first for this to work.
http://scitools.org.uk/cartopy/docs/v0.13/index.html
Add annotations for locations using their lon/lats.
Author: DAV
"""
import cartopy.feature as cfeature
import cartopy.crs as ccrs
i... |
0411f2bdbf14c5b49d212f594b183011a1bb8e97 | addie293/Conveyor-Belt-and-Waste-Management-System | /conveying_workshop/internal_process/InternalProcess_conveyingWrkshop.py | 3,326 | 3.890625 | 4 | import random
num=random.randint(0,1)
initiate_the_process=input("please type in START to initialise:")
case_sensitive_input1=initiate_the_process.lower()
if case_sensitive_input1=='start':
print("checking the availability of green jack")
if num==1:
print("jack status is okay")
print("now checki... |
c0d24f1b69d2875ab8ae7a9d36d27aa09a09b075 | satsumas/Euler | /prob4.py | 852 | 4.34375 | 4 | #! user/bin/python
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import itertools
def backwards(n): #finds reverse of a number
s = str(n)
l... |
2d495b12270ac97a889dac65e3d8bcc4d7da94dc | suzy56/PythonPractice | /character01/strText.py | 603 | 3.9375 | 4 |
print(len('hello world'));
#格式化整数和浮点数
print('%2d-%02d' % (3.333,1.222));
print('%.2f' % 3.1415926);
# %% 转义 % 号 ,当字符串里有%号输出时
print('growth rate : %d %%' % 7);
# format() 函数使用
print('hello,{0},成绩提升了{1}%'.format('suzy56',8.222));
print('hello,{0},成绩提升了{1:.1f}%'.format('suzy56',18.2222));
#小明的成绩从去年的72分提升到了今年的8... |
9448edec306d94674505d6ac6a5bab24192d7044 | prietoana321/Ejercicios_Rosalba | /Listas.py | 1,395 | 3.875 | 4 |
#CREACION DE LISTAS
#PERTENECE A ANA CECILIA PRIETO GRUPO 1
#listas
lista=[]
print(lista)
#lista semana
listadias=["Lunes","Martes","Miercoles","Jueves","Viernes"]
print(listadias[0])
#lista semana
listadias=["Lunes","Martes","Miercoles","Jueves","Viernes"]
print(listadias[-1])
#lista semana
listadias=["Lunes","... |
48cb87e76a747c7f0639c65dd74e01cec56e4c45 | 7hacker/data-structures-algorithms-in-python | /random/graph_dfs.py | 1,042 | 3.6875 | 4 | '''
graph dfs traversal
'''
from graph import Graph
def visit(node):
print("Visiting Node :" + str(node))
return
def dfs(g, startAt, visited):
startNode = g.getVertex(startAt)
if not visited[startAt]:
visit(startAt)
visited[startAt] = 1
for neighbor in startNode.getConnections():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.