blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
87ba541139b64b02e41df0d2a668c1a2dce5495b | riteshbisht/dsprograms | /arrays/rearrangement/problem2.py | 980 | 4.21875 | 4 | """
Write a program to reverse an array or string
Given an array (or string), the task is to reverse the array/string.
Examples :
Input : arr[] = {1, 2, 3}
Output : arr[] = {3, 2, 1}
Input : arr[] = {4, 5, 1, 2}
Output : arr[] = {2, 1, 5, 4}
"""
def reverse_whole_string(k):
start = 0
end = len(k)
new_... |
a9bd908e67ca130617cb6c7fa37a0f39ee5f8c33 | RafikFarhad/Bioinformatics_Codes | /solutions/ba1c.py | 526 | 3.609375 | 4 |
def Reverse(Dna):
tt = {
'A' : 'T',
'T' : 'A',
'G' : 'C',
'C' : 'G',
}
ans = ''
for a in Dna:
ans += tt[a]
return ans[::-1]
def main(infile, outfile):
# Read the input, but do something non-trivial instead of count the lines in the file
inp = lines =... |
58318f29ce62fb824dd12e7b2b0a954b1f13b8a6 | julian-chan/league-trivia | /flask_api/scripts/ExtractItemData.py | 1,844 | 4.03125 | 4 | """
This script is used to extract and create a new JSON file containing the key data fields that
are needed for League Trivia from the item.json data downloaded from Data Dragon. This is
because item.json contains a lot of data that isn't needed for League Trivia, so we only keep
the data fields tha... |
b2ef6e37a895908e809f0c2177eae44931bf7141 | vsrkrishnan/python-exercises | /the-game-of-snap/snap.py | 1,978 | 3.921875 | 4 | import itertools
import random
match_conditions = {1: "Suite",
2: "Face value",
3: "Both"}
suites = ('Hearts', 'Spades', 'Diamonds', 'Clubs')
values = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
print "\nWelcome to Snapster!!"
print "========... |
128e483c5bafbcac95584b21a960ca829274321b | Chiafl/Wallbreakers-Cohort-3 | /Solutions/Week 5/longest-univalue-path.py | 1,080 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
self.ans = 1
self.helper(root)
return self.ans-1
... |
323d64b2cd937ab44ba6450a603b8387563e1b55 | RamiroAlvaro/desafios | /maximum_subarray.py | 1,941 | 4.125 | 4 | """
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
For example, given the array [−2, 1, −3, 4, −1, 2, 1, −5, 4],
the contiguous subarray [4, −1, 2, 1] has the largest sum = 6.
"""
def max_subarray_quadratic(list_):
if not list_:
return list_, 0
... |
932095dd38103ba872f14b3577cc253eeff80177 | osnipezzini/PythonExercicios | /ex067.py | 524 | 4.09375 | 4 | '''
Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo.
'''
tabuada = cont = 0
while True:
cont = 0
numero = int(input('Digite um número que lhe mostrarei a tabuada: '))
if nume... |
f913ad25130197a143c0743aab785e249e3d6f3b | OtavioAMota/Maratona_Programacao | /Beginner/Salary with Bonus.py | 156 | 3.640625 | 4 | Name = str(input())
Salary = float(input())
Total_sell = float(input())
Total_Salary = Salary + (Total_sell*0.15)
print("TOTAL = R$ %.2f" % Total_Salary)
|
61887c76a3886ad7e328b37a1b4c1cc72ad35d5b | xshi0001/base_function | /mouse_simulation_test.py | 1,694 | 3.5 | 4 | # -*-coding=utf-8-*-
__author__ = 'Rocky'
import pyautogui as pg
import pyautogui, time
def get_pos():
cur_x, cur_y = pg.position()
print cur_x, cur_y
def basic_api():
x, y = pg.size()
print x, y
'''
pg.moveTo(300,300,2)
pg.moveTo(300,400,2)
pg.moveTo(500,400,2)
pg.moveTo(500,30... |
e62f11aba739f45933a76d0bfb2a5616707c6302 | jeremiahduclanj/peanut | /tettt.py | 678 | 3.765625 | 4 | #group members: George, Jeramiah, Kunsh, Yidam
import turtle as trtl
painter = trtl.Turtle()
#ask user for the equation, slope, and y-intercept (POSITIVE NUMBERS ONLY)
eq = int(input("Input Equation in y = mx + b form: "))
slope = int(input("What is the slope?: "))
yint = int(input("What is the y-intercept?: ")... |
268724098e09bb2da44406bbb3107ac1ad4e9dd3 | NileshProgrammer/Python-Project | /Next_Prime_Number.py | 611 | 4.09375 | 4 | import math
list = [ ]
n = int(input("Please enter the number to find the prime factor:"))
def prime_factor(n):
while n % 2 == 0:
n = n / 2
list.append(2)
for i in range(3,int(math.sqrt(n))+1,2):
while n % i == 0:
list.append(i)
n = n /i
if n > 2 :
... |
27150fcba619ba3a4b11b0edd6ac29a364218b3a | Bravo555/advent-of-code | /03/03.py | 1,145 | 3.5 | 4 | from functools import reduce
with open('input.txt') as f:
data = list(map(str.strip, f.readlines()))
data = [seq.split(',') for seq in data]
# assume central port as (0, 0)
def visited_coords(move, origin):
length = int(move[1:])
unit = {
'U': (0, 1),
'D': (0, -1),
'L': (-1, 0... |
6cd6697a08a953d03c0f52f3afd31549ae22fbb6 | iamakhildabral/Python | /CommonCode/reverse word with delimiter.py | 267 | 3.609375 | 4 | user_input = "My name, I dont wanna tell"
d = user_input.split(" ")[::-1]
for each in d:
f = each.split(",")
i = len(f)
for x in f:
if i>1:
print(",")
print(f)
i=0
|
1311f8997479924d64bf24c5f0ad6c43878df3b4 | anonymous-iclr-3518/code-for-submission | /ethicml/data/load.py | 1,769 | 3.59375 | 4 | """Load Data from .csv files."""
from pathlib import Path
from typing import List, Optional
import pandas as pd
from ethicml.utility import DataTuple
from .dataset import Dataset
__all__ = ["load_data", "create_data_obj"]
def load_data(dataset: Dataset, ordered: bool = False) -> DataTuple:
"""Load dataset fro... |
bc45317d8d72de0d031d90072a587005379b224d | hushaoqi/LeetCode | /155.py | 1,770 | 4.1875 | 4 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self._data = []
self._minData = []
def push(self, x: int) -> None:
"""Add element x to the top of stack"""
self._data.append(x) # new item stored at end of list
if ... |
5e895d88bdd03c7f93febba64bfc0f48249be1af | Leekailklk/untitled_dingtalk | /Cocacola.py | 300 | 3.671875 | 4 | class CocaCola:
formula=['coffeine','sugar','water','soda']
def drink(self):
print('energy')
coke_for_me=CocaCola()
coke_for_you=CocaCola()
print(CocaCola.formula)
coke_for_me.drink()
print(coke_for_you.formula)
for element in coke_for_me.formula:
print(element)
print("\N{Cat}") |
bdfe13adbb3b1d57212bf4f7bb864a40c43d6320 | Yet-sun/python_mylab | /Lab_projects/lab4/Lab4_04.py | 380 | 4 | 4 | '''
需求:编写一个递归函数,实现Fabonacci数列
'''
def Fabonacci(n: int) -> int:
if n == 1 or n == 2:#Fabonacci函数中,n=1和n=2是特殊值
return 1
else:
return Fabonacci(n - 2) + Fabonacci(n - 1)
def main():
n = int(input("请输入一个整数:"))
print("Fabonacci函数的结果为:" + str(Fabonacci(n)))
main()
|
675d653e3ced442f10418b7e6fb070870ccb00dc | sumit2798/GFG | /Stack/parenthesis_checker.py | 881 | 3.765625 | 4 | #Python 3
'''
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.
'''
# pop element from 1st stack
def pop1(a):
global top1
if top1 == -1:
r... |
fa79f40600fe70e07f0c128800140530dab8b8f5 | MoKamalian/CSCI2202 | /Solutions for lab 1-B nd assing1 nd test/Lab 7/vehulstEquation.py | 689 | 3.8125 | 4 |
# Create an initial value for both equations, Verhulst and Alternate.
V = 0.01
A = 0.01
# Set the value of r
r = 3
# Print the output header line to the screen
print("Verhulst1\t\tVerhulst2\t\tDifference")
# Recalculate where each algorithm deviates. Perform 50 such recalculations.
for i in range(50):
... |
556b8870d477d0f738f36f0f03d51429321937b5 | Erivaldojelson/Calculadora | /day1.py | 140 | 3.8125 | 4 | >>> print("Hello; world!")
Hello; world!
>>> exit()
>>> if 5 > 2:
print("Five is greter than two!")
Five is greter than two!
>>> |
8b2fee8d92c74d593e045a07f35df15dd6241c88 | harris-ippp/hw-6-aeskenazi | /e1.py | 1,862 | 3.5625 | 4 | #!/usr/bin/env python
import requests
from bs4 import BeautifulSoup as bs
addr = "http://historical.elections.virginia.gov/elections/search/year_from:1924/year_to:2016/office_id:1/stage:General"
resp = requests.get(addr) #download url
html = resp.content #look at the html content of that url
soup = bs(html, "html.par... |
e6f543ee4573a4daf27e6e208dee0bbe7db056a6 | yuko29/DHT22-dashboard | /test.py | 644 | 3.640625 | 4 | import sqlite3
sqliteConnection = sqlite3.connect('data.db')
cursor = sqliteConnection.cursor()
sql = "select Time, Temperature, Humidity from DHT22 limit 10"
print(sql)
cursor = cursor.execute(sql)
data = {
'Header': [],
'Time':[],
'Temperature': [],
'Humidity': []
}
header = list(map(lambda x: x[0], c... |
c96fe471e6409ce502f5d2f4ca56f6e59f9d13dc | pythonbtes/nandini | /btes/simple_calculator.py | 2,072 | 3.828125 | 4 | from tkinter import *
window=Tk()
window.title("simple calculator")
window.configure(background="#17A589")
window.geometry("370x150")
window.resizable(0,0)
expression=""
def display(num):
global expression
# concatenation of string
expression = expression + str(num)
# upd... |
779944a0d9c5e15201a52ecf6200904fb581a368 | AnkitAvi11/Data-Structures-And-Algorithms | /Data Structures/Queues/QueueList.py | 1,447 | 4.46875 | 4 |
# class node to create a node for the queue linked list
class Node :
def __init__(self, val) :
self.val = val
self.next = None
class Queue :
# contructor of the queue class
def __init__(self) :
self.front = None
self.rear = None
# method to insert an elem... |
d3b13a5f10b5e20a8a726f42f6d372fede665021 | Suraj-sati/programming-using-python | /remove_empty_tuples_in_list.py | 206 | 4.03125 | 4 |
l=[]
s=int(input("enter the size of list :"))
for i in range(0,s):
m=input("enter the element in list:")
l.append(m)
t=list(filter(None,l))
print ("list after removing empty elements :",t) |
cd8b91ef3bf1ab9c87ebf93b5922b3a57982037a | gerrymandr/exhausting_splits | /hack3.py | 8,318 | 3.609375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 4 10:56:22 2017
@author: christy
"""
import networkx as nx
import csv
import sys
import numpy as np
import matplotlib.pyplot as plt
plt.interactive(False)
#using csv
def create_graph(index,file):
G=nx.Graph()
f = open(file)
reader = ... |
507da2f51cec77c87b07248a5bb7485e713a1d90 | L200180039/praktikum-ASD | /MODUL - 1/14.py | 315 | 3.796875 | 4 | #14
def formatRupiah(a) :
a = list(str(a))
b = len(a)
if b % 3 == 0 :
b = int(b/3) - 1
else :
b = int(b/3)
n = 0
for i in range(b) :
x = -3*(i+1)
a.insert(int(x)+n,".")
n = n - 1
a = "".join(a)
print("Rp "+a)
|
674c8c05dc66322924c290c52b2d6bb09c95b76f | Peixinho20/Python | /python/mundo2/a14/d62.py | 670 | 3.921875 | 4 | #Até a aula 14
'''
Melhore o desafio 61 perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra
quando ele disse que quer mostrar 0 termos.
'''
a1 = int(input('Primeiro termo: '))
r = int(input('Razão: '))
termo = a1
cont = 1
total = 0
mais = 10
while mais != 0:
total = total + mais # ... |
edc67b4ddf0b6ff2f3da3aa536e1ef2379e764b6 | akshatakulkarni98/ProblemSolving | /DataStructures/MSFT/add_two_num_stored_rev.py | 1,050 | 3.734375 | 4 | # https://leetcode.com/problems/add-two-numbers/
# TC:O(N)
# SC:O(N)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
... |
0c82160da861b9c3942862d706c04526fc26c1d2 | chesneynyame/CLI-Application | /mini-project-csv-file-dict-2.1.1 CSV input.py | 45,342 | 3.671875 | 4 | # # WK1
# In this week we'll be building out the foundation of your app, in particular, the UI aspect.
# This will make use of your ability to print to the screen, clear the screen, accept user input, and create a basic `list` data structure.
# Try to make good use of functions for repetitive tasks.
# ## Goals
# A... |
e2d162869509023697e5231bdf2d5b214ced5f26 | rmesseguer/number_game | /number_game.py | 1,430 | 4.09375 | 4 | import random
robot_score = 0
player_score = 0
while True:
num = random.randint(1,10)
good_guess = False
while not good_guess:
try:
guess = int(input('Guess a number between 1 and 10: '))
if guess < 1 or guess > 10:
ra... |
699210565e0d9e0e1c8cd00597f5226e45efa373 | Vershinin100797/HomeWork_Vershinin_Ivan | /Zanyatie11/hw11_2.py | 2,172 | 3.515625 | 4 | import sys
import threading
import time
class Locks(object):
def __init__(self, initial):
self.lock = threading.Condition(threading.Lock())
self.initial = initial
def up(self):
with self.lock:
self.initial += 1
self.lock.notify()
def down(self):
w... |
a63b5032e669f5ca738669811232abf037a18227 | DiegoAnas/Group39-ML-Ex3 | /util/demoPlot.py | 2,628 | 3.5 | 4 | # Example plots
from matplotlib import pyplot as plt
import os
import numpy as np
import cv2
from PIL import Image
def main(demoImage):
# For Notebook
#%matplotlib inline
# For OpenCV (need Version 2.4+) for Python 2.7
os.chdir("..")
print ("Showing demo feature extraction on image " + demoImage)
... |
16d3b9e10964c6aa3d2993a414dca57b842fb2fd | jbw772713376/PythonStudy | /if...eles.py | 318 | 4 | 4 | height = 1.75
weight = 80.5
BMI = weight/pow(height, 2)
if height < 0 or weight < 0:
print("参数错误!")
exit(0)
if BMI < 18.5:
print('过轻')
elif 18.5 <= BMI <25:
print('正常')
elif 25 <= BMI < 28:
print('过重')
elif 28 <= BMI < 32:
print('肥胖')
else:
print('严重肥胖') |
cb37549bcd999fc40e657e23f57c96b0fc45de3c | tamyrds/Exercicios-Python | /Mundo_2_Python/Decisao/desafio28.py | 222 | 3.9375 | 4 | import random
num = int(input('Digite um número: '))
print("PROCESSANDO...")
adv = random.randint(0,5)
if num == adv:
print('Voce acertou o número')
else:
print(f'Voce não acertou e o número correto é {adv}') |
7a8cd933bf3ea7a0bedad13651e0594fd7460d6d | Qinpeng96/leetcode | /559. N叉树的最大深度.py | 1,104 | 3.828125 | 4 | """
[559. N叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/)
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
:
self.matrix = [array for array in args]
self.size = len(args), len(args[0])
def __str__(self):
return '\n'.join([
' '.join([str(el) for el in array]) for array in self.matrix
])
def __add__(self, other):
added = [... |
405c5c3bd4895637a5cfa22b242aca58eb8dc76d | anilgeorge04/learn-ds | /datacamp/merge-tables/query.py | 689 | 3.890625 | 4 | # Query Method and create a pivot table
import pandas as pd
import matplotlib as plt
# Merge gdp and pop on date and country with fill
gdp_pop = pd.merge_ordered(gdp, pop, on=['country','date'], fill_method='ffill')
# Add a column named gdp_per_capita to gdp_pop that divides the gdp by pop
gdp_pop['gdp_per_capita'] =... |
fa348c571e9e272907a145293b503dc0541c0d52 | kentfrazier/euler | /Python/p024.py | 1,060 | 4.125 | 4 | # A permutation is an ordered arrangement of objects. For example, 3124
# is one possible permutation of the digits 1, 2, 3 and 4. If all of the
# permutations are listed numerically or alphabetically, we call it
# lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
#
# 012 021 1... |
cc548e9b8c35748b5c9dd92bcd5057d8bebfbbc4 | kiran0712/stock-portfolio-analysis | /stockportfolio.py | 13,514 | 3.53125 | 4 |
''' Descriptive data : Non graphical - mean, SD, variance
Graphical data : MA, MACD, Mean, basic stock price graph, trend lines,
Weighted moving average, Monthly returns for the stock '''
# Import statements
import sys
import pandas as pd
import numpy as np
import statsmodels.api as sm
import pandas_data... |
4bec38ebcf0901b4720154c4cf185c5b03805379 | ashwani1310/Simple-Linear-Regression | /simple_liner_regression_self.py | 1,627 | 4.1875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('input here the destination of any csv file which has single input feature and a label')
Single_feature = data.iloc[:, :-1].values #Here the label is last column and the feature is the first column
Label = data.iloc[:, 1].values... |
11096870b2418757017d08cf043843812085547c | sidro/excodpy | /python-exemple/capitalizare.py | 104 | 3.828125 | 4 | def capitalise(string):
return string[:1].upper() + string[1:].lower()
print(capitalise("amara"))
|
0930e0518482836c24c07adf53403fad4ef304c7 | Enfors/CursMon | /cursmon/curs_ui.py | 7,321 | 3.5625 | 4 | """
Curses-based User Interface for CursMon.
"""
import curses
WHITE = 1
RED = 2
BLUE = 3
YELLOW = 4
CYAN = 5
GREEN = 6
MAGENTA = 7
class UI(object):
"""
The Curses-based User Interface class.
"""
def __init__(self, scr):
self.lines = curses.LINES
self.cols = curses.COLS
sel... |
e57567e4200cdaf5105a5dfebf1969500502b151 | rosauraruiz-lpsr/class-samples | /RosauraRuiz/partner.py | 360 | 3.671875 | 4 | import turtle
def makeSquare(myTurtle, side):
myTurtle.forward(side)
myTurtle.left(60)
myTurtle.forward(side)
myTurtle.left(60)
myTurtle.forward(side)
squeak = turtle.Turtle()
length = 100
while length > 0:
makeSquare(squeak, length)
squeak.right(5)
len... |
007dfa5fd6a5d9714f418e02632ec1fc6ba5cd50 | xiongxiong109/algorithm_study | /py/algorithm/bin_search.py | 501 | 3.84375 | 4 | # 二分法查找
from math import floor
# 只适合有序的数组
def bin_search(search_list, target):
upper = len(search_list) - 1
lowwer = 0
# search_list.sort()
while lowwer <= upper:
mid_len = floor((upper + lowwer) / 2)
cur_item = search_list[mid_len]
# print(mid_len)
if cur_item < targe... |
f5302b6fe54155b07183ab8d839adf388bc01210 | shreyanse081/Some-Algorithms-coded-in-Python | /QuickSelect.py | 1,624 | 4.09375 | 4 | """
QuickSelect finds the kth smallest element of an array in linear time.
Amir Zabet @ 05/08/2014
"""
import random
def Partition(a):
"""
Usage: (left,pivot,right) = Partition(array)
Partitions an array around a randomly chosen pivot such that
left elements <= pivot <= right elements.
Running time: O(n)
... |
2a21c85841e5d83d658eece68f6ad7fc9894ea0a | swrnv/hackerrank-30daysofcode | /Day 10- Binary Numbers.py | 255 | 3.515625 | 4 | def find_max_ones(n):
if not n:
return 0
bin_num = bin(n)[2:]
return len(max(bin_num.replace('0', ' ').split(), key=len))
if __name__ == '__main__':
n = int(input())
max_ones = find_max_ones(n)
print(max_ones)
|
46b12b9dc6c00a71f82a5cbc84298197a95eb3f7 | 1769778682/python02 | /work/work_03.py | 234 | 3.84375 | 4 | # 获取键盘输入的一个数字, 判断该数字是奇数还是偶数, 输出对应结果
# 1,获取键盘中的一个数字
num = int(input('请输入一个数字:'))
if num % 2 == 1:
print('奇数')
else:
print('偶数') |
99277f74f2ca4445ff0c4dd4f45d86c10af6d123 | daisuke0728/python_practice | /4_45.py | 219 | 3.734375 | 4 | n = 14
if n > 15:
print("とても大きい数字")
#elifを用いて11以上15以下の時に中くらいの数字と出力
elif n >= 11:
print("中くらいの数字")
else:
print("小さい数字")
|
7e65a81ef5a45d6d2d44a9ba149164eba85afc90 | dianalow/RiceFOC | /01_InteractivePythonProgramming/spock.py | 1,145 | 4.15625 | 4 | # Written by : Diana Low
# Last updated : 9 April 2014
# Coding assignment for Rice University's
# Interactive Python Programming course
# Game : Scissors, Paper, Spock
# Run on codeskulptor.org
def name_to_number(name):
if(name=="rock"): return 0
elif(name=="Spock"): return 1
elif(name=="paper"): return ... |
923db8bcfe1406e74cd8b3742fad9418667d238e | burkan96/Monty_Hall_Simulation | /Monty Hall problem.py | 3,020 | 4.375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Monty Hall simulation for *n* doors
# Suppose you're on a game show, and you're given the choice of n doors: Behind one door is a car; behind the others, goats.
# You pick a door, say No. k, and the host, who knows what's behind the doors, opens opens *n-2* losing doors and ... |
6408b4b1ae5688712524e27571ba4fc20c37910a | mbaty001/experimental | /algorithms/basics/parenthesis.py | 514 | 3.703125 | 4 | # Check whether parenthesis are properly formatted:
# ()()() - True
# ((() - False
# )(() - False
def bla(string: str) -> bool:
... count = 0
... for s in string:
... if s == "(":
... count += 1
... elif s == ")":
... count -= 1
... if count < 0:
... ... |
40c5962c7cbd04b867982d42f7bb6ed7c0afc478 | ljm516/python-repo | /algorithm/stack/example.py | 1,719 | 4.15625 | 4 | # 调用栈
def greet2(name):
print("how are you, {name}?".format(name=name))
def bye():
print("ok, bye!")
def greet(name):
print("hello, {name} !".format(name=name))
greet2(name)
print("greeting ready to say bye...")
bye()
greet("ljming")
'''
说明:
调用 greet(), 计算机为该函数分配一块内存。
... |
6583750e64ff7f6d8ed7e75d9f33b13fa79df894 | mostipaka/pythonintask | /BITs/2014/Mostipaka_A_E/z3v15.py | 720 | 3.875 | 4 |
#Задача N3. Вариант 15
#Напишите программу, которая выводит имя "Лариса Петровна Косач-Квитка", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# Mostipaka A. E.
# 29.02.2015
lesy=input("Под каким же псевдонимом известена Лари... |
c339eb426e9fc0fe91c3423a57a5909710fb395b | KadenRamirez/ICS2019_2020 | /ICS_03_Ramirezk21/Program.py | 1,296 | 3.984375 | 4 | import math
import sys
"""
Kaden Ramirez
This program combines all of the previous
java programs into a gaint python frankenprogram
"""
print(" /\\\n /__\\\n /\\ /\\\n /__\\/__\\")
try:
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
r1 = (... |
ea181ca47afb8f73b5c4d3364615815c00e8cfff | DayGitH/Python-Challenges | /DailyProgrammer/DP20140728A.py | 1,447 | 4.125 | 4 | """
[7/28/2014] Challenge #173 [Easy] Unit Calculator
https://www.reddit.com/r/dailyprogrammer/comments/2bxntq/7282014_challenge_173_easy_unit_calculator/
# [](#EasyIcon) _(Easy): Unit Calculator
You have a 30-centimetre ruler. Or is it a 11.8-inch ruler? Or is it even a 9.7-attoparsec ruler? It means the same
thing,... |
2f451f5a058b17f29c47f3487fe409f45cde8135 | vladn90/Algorithms | /Backtracking/subsets.py | 2,902 | 3.5 | 4 | """ Problem statement:
https://leetcode.com/problems/subsets/description/
https://www.interviewbit.com/problems/subset/
"""
class SolutionLeetcode:
def subsets_brute(self, nums):
""" Returns an array of tuples, where each tuple is a subset of original
array nums.
"""
result = set()... |
c797ae600e795ad6a0cbd54ec0fae48ce422d142 | vaibhav-rbs/RealPython-VB | /flask-hello-world/sql/02_sql.py | 519 | 4.15625 | 4 | # Create a SQLite3 database and table
# import the sqlite3 library
import sqlite3
# create a new database if the database does not already exist.
conn = sqlite3.connect('new.db')
# get a cursor object used to execute SQL commands
cursor = conn.cursor()
# create a table
cursor.execute("""INSERT INTO population ... |
1810c8f4d6c8cf9b4ad6a665db83d9f3b2e647eb | YashChitgupakar9/practice | /029.py | 1,318 | 4.5 | 4 | class Football:
# pass doesn't do anything. its just like a statement.. instead keep class as an empty, if you do wish to have any statements in class, then you keep 'pass'
def __init__(self, x):
print (x)
def condictions(self):
print ("FIFA rules...")
Football(23749)
#1. Whenever you create an object, It... |
cec499c4f49117e70cb0d7ef11b69ed07f34282c | killbug2004/Snippets | /Algorithm/algorithm/compress.py | 833 | 4.34375 | 4 | '''
String compression using the counts of repeated characters. For example, the string aabcccccaaa would become
a2blc5a3. If the "compressed" string would not become smaller than the original string, the method returns the original string.
'''
def compress(string):
if len(string) == 0:
return string;
old = list... |
dc8718db06fd6f1f3eb28880805630141a5ff687 | MassimoLauria/informatica2019 | /src/code/algoritmi.py | 5,764 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Codice utile per le dispense di Informatica
Il modulo contiene alcune funzioni utili per le dispense, in
particolare contiene le implementazioni degli algoritmi visti
a lezione.
Verrà regolarmente esteso quindi controllate che non vi siano
aggiornamenti disponibili p... |
79cad5c421799d452ffaf4f2fd98d2c316658359 | Pritamthing/python-assignment | /assignment34.py | 451 | 4.0625 | 4 | input1=int(input("Enter a size of dict1: "))
dict1={}
for i in range(input1):
key=input("Enter a key: ")
dict1[key]=input("Enter a value at "+str(i+1)+": ")
input2=int(input("Enter size of dict2: "))
dict2={}
for j in range(input2):
key=input('Enter a key: ')
dict2[key]=input("Enter a value at "+str(j+1... |
22c3f733b887f335b1ea7483323a353a2454ae4f | dudtj0904/python-ch2.4 | /practice12.py | 398 | 3.78125 | 4 | # 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에
# 출력해보세요. 1부터 99까지만 실행하세요
for i in range(1,100) :
s = str(i)
length = len(s)
count = 0
for j in range(0, length) :
if int(s[j]) != 0 and int(s[j]) % 3 == 0 :
count += 1
if count != 0 :
print(s, '짝'*count)
|
7bd75497422f16c7fdbf5e9c067c292730e3c425 | amrutaDesai/pythonPractice | /pythonFundamentals/section7/dictionaryPythonNotes.py | 1,444 | 4.375 | 4 | def dictionaryNotes() :
print('1. Dictionary contains key-values pair and keys are like lists indexes')
print('2. Dictionary are mutable, variables hold the reference to dictionary values,not the dictionary value itself')
print('3. Dictionary are un order, there is no first key-value pair in the dictionary'... |
8363e898340f31b6cf0db313e1196f92684f241a | Ejas12/pythoncursobasicoEstebanArtavia | /dia3/tarea2.py | 883 | 3.984375 | 4 | ####ejercicio1###
# Crear líneas de código en Python que calcule el promedio de los valores contenidos en una lista.#####
myvalues = [5,1,2,3,8,12]
average = sum(myvalues)/len(myvalues)
print("Promedio de los numeros es %.2f" % average)
#####Ejercicio 2###
# Escriba un código en python que determine cual grupo de ... |
682349d59750ac4927cb920a24ac581968b0138f | Panther010/learning | /Python/ds_and_algo/array/array_07-unique-characters-in-tring.py | 261 | 3.71875 | 4 | def unique_char(s):
seen = set()
for char in s:
if char in seen:
return False
else:
seen.add(char)
return True
print(unique_char(''))
print(unique_char('goo'))
print(unique_char('abcdefg')) |
07ade40d4bf4b6b69bfead33cb3a92166b682827 | lastbyte/dsa-python | /problems/medium/validate_bst.py | 1,719 | 4.15625 | 4 | '''
98. Validate Binary Search Tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the no... |
d7dbd57c3b404a07b7814d5ee2b992834e3fece9 | spenc53/scum_game | /server/game/utils/game_util.py | 2,403 | 3.71875 | 4 | from game.card import Card
from game.player import Player
class GameUtil():
def isValidMove(playerHand: "list[Card]", move: "list[Card]", lastMove: "list[Card]") -> bool:
"""Checks if a given move is valid
Args:
player (Player): The hand of the player making the move
move ... |
e20c61c0982c291a76bea9f4a65ea0d4d2ebaec2 | lcqbit11/algorithms | /medium/largest_number.py | 539 | 3.71875 | 4 |
def largest_number(nums):
if not nums:
return
n = len(nums)
for i in range(n):
for j in range(n-1-i):
if str(nums[j])+str(nums[j+1]) < str(nums[j+1])+str(nums[j]):
nums[j] = nums[j] + nums[j+1]
nums[j+1] = nums[j] - nums[j+1]
... |
4a6588c26e5ea39f3b4a8d4192c8fec56de70622 | max87-arch/disaster-responses-project | /models/misc/utils.py | 500 | 3.515625 | 4 | import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
def tokenize(text):
word_list = word_tokenize(text.lower())
only_words_list = [word for word in word_list if... |
f44361088c8a60f2092fe25d428ffbbfc6a122e3 | Adib234/Leetcode | /maximum_number_of_coins_you_can_get.py | 444 | 3.5 | 4 | class Solution(object):
def maxCoins(self, piles):
"""
:type piles: List[int]
:rtype: int
"""
start=len(piles)-1
count=0
total=0
piles.sort()
alternate=False
while count!=len(piles)//3:
start-=1
alternat... |
66a00c89f745f81daacf3907f4f528d9623efb09 | MarvelICY/DSAP | /Algorithms/binary_search.py | 1,076 | 4.1875 | 4 | #!usr/bin/python
# -*- coding:UTF-8 -*-
'''
Introduction: Binary search
Created on: Oct 24, 2014
@author: ICY
'''
#-------------------------FUNCTION---------------------------#
class Solution:
# the array must be sorted from small to large order
def binary_search(self, num, value):
left = 0
... |
db324305b6356aabbc0aafa217cc6a04507a6963 | carlosbarcelos/advent-of-code-2018 | /day02/day02.py | 1,681 | 3.703125 | 4 | '''
Advent of Code: Day 2
Inventory Management System
'''
from collections import Counter # Count characters in string
# Read in the data
f = open('day02.txt', 'r')
data = f.read().split()
f.close()
def partOne():
twoTimes = 0
threeTimes = 0
for id in data:
# Create count of each letter
... |
b889373f14a8765740637b14ec0c40d4190497ed | denck007/scraping | /hardwareswap_scraper/parse_pushshift_data.py | 3,849 | 3.6875 | 4 | '''
This script turns the json files from pushshift and looks for a price in the post text.
A 'price' is defined as the numbers between a '$' and the following non numeric charaters. It also matches the case where the pattern is non-numeric, then numeric price, then $
This creates raw data files. All this data needs t... |
f94cd7ed784577a29dd86b94b46e7b2dba75e9aa | gtokusum/CSCI-C200-Fall-2020 | /Laboratory/Debugger/magic.py | 166 | 3.546875 | 4 | lst = [[1,2], [3,4],[5,6],[7,8]]
def magic(x):
s = 0
for y in x:
z=y[0]
s += z
return s
if __name__ == '__main__':
print(magic(lst)) |
6bf39aac603609e19c85b64c9d6e29304fa14062 | constructor-igor/TechSugar | /pythonSamples/tips/progress_bar_sample.py | 575 | 3.578125 | 4 | #
# conda install progressbar2
#
# https://stackoverflow.com/questions/3002085/python-to-print-out-status-bar-and-percentage
# https://anaconda.org/conda-forge/progressbar2
#
import numpy as np
import progressbar
from time import sleep
def show_progress_bar():
with progressbar.ProgressBar(maxval=20, widgets=[p... |
758d44c4ab8fac7b99ba40410b77c3c017c7389c | LucasDiasTavares/Python | /medias.py | 311 | 3.609375 | 4 | nota1 = input ("Digite a primeira nota: ")
nota2 = input ("Digite a segunda nota: ")
nota3 = input ("Digite a terceira nota: ")
nota4 = input ("Digite a quarta nota: ")
n1 = int(nota1)
n2 = int (nota2)
n3 = int(nota3)
n4 = int (nota4)
media = (n1+n2+n3+n4)/4
print ("A média aritmética é ", media)
|
0ec8c5bab8830f5120227960ad3aa1708f3de5fd | sophialuo/CrackingTheCodingInterview_6thEdition | /16.20.py | 1,115 | 3.890625 | 4 | '''
T9: On old cell phones, users typed on a numeric keypad and the phone would provide a list of words that matched these numbers. Each
digit mapped to a set of 0-4 leters. Impelment an algorithm to return a list of matching words, given a sequence of digits. You are
provided a list of valid words (provided in what... |
fe5eaff85b34ed058b5b93fceaef720dd2499199 | benningtoncompling/project2-eastasiantokenization-kelseybroadfield | /japanese_tokenizer.py | 1,972 | 3.625 | 4 | #
# Comp Ling PROJECT #2- Japanese Tokenization
#
# March 2019
# Author: Kelsey Broadfield kelseybroadfield@bennington.edu
#
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
# how I run it on my computer bc I don't know how to use the terminal on my laptop
# input_file = 'in.txt'
# output_... |
c6c63f2cc956f735014834b27967f3ddcc63415f | mattsuri/unit4 | /warmpup11.py | 173 | 3.71875 | 4 | #Matthew Suriawinta
#3/26/18
#warmup11.py
def prime(num):
for i in range (2,num):
if num % i == 0:
return False
return True
print(prime(3)) |
63542bceb1ba276c4d0392fc124820698e51ce7d | R3tr093/ToDouxLiss-t | /Python/remind/prout/string.py | 9,267 | 3.984375 | 4 | # This script is writed for remind me some tips about how to use string object in Python
import os
def clear():
os.system('clear')
os.system('cls')
newLine = "\n"
def frame (param):
print(newLine)
print('|------------------------------------------------------------|' + newLine)
print('| ... |
15726ab43764bf3651a59b4d1723b9e891cd67d9 | evanwangxx/leetcode | /python/1160_Find_Words_That_Can_Be_Formed_by_Characters.py | 1,527 | 3.875 | 4 | # You are given an array of strings words and a string chars.
# A string is good if it can be formed by characters from chars (each character can only be used once).
# Return the sum of lengths of all good strings in words.
#
# Example 1:
# Input: words = ["cat","bt","hat","tree"], chars = "atach"
# Output:... |
d3e42593aef1dfa1346240ce7b4fdc98adb99701 | kilicmustafa/Python | /Python Temel/Metin İslemleri/Split_replace_örnek.py | 1,104 | 3.59375 | 4 | #SUBstring
mesaj = "MERHABA DÜNYA"
mesaj_2 = mesaj[:5]
print(mesaj_2)
mesaj_3 = mesaj[1:8]
print(mesaj_3)
mesaj_4 = mesaj[3:]
print(mesaj_4)
#LEN uzunluk
metin = "UZUNLUNLUK LEN"
metin_sonkarakter = metin[len(metin)-1:len(metin)]
print(metin_sonkarakter)
#LOWER VE UPPER CASE
text = " Ali İLE veli El ele "
... |
4da2d6f15a15d40077055790e650868efc623e5e | nicolasgasco/CodingNomads_Labs | /06_functions/06_01_tasks.py | 854 | 4.0625 | 4 | '''
Write a script that completes the following tasks.
'''
# define a function that determines whether the number is divisible by 4 or 7 and returns a boolean
def isdivisible_single(num):
if num % 7 == 0 or num % 4 == 0:
return True
else:
return False
# define a function that determines whet... |
5f38c25fff9915754f691ede33a5c72f43acd3f4 | paalso/hse_python_course | /3/3-10.py | 1,134 | 4.46875 | 4 | # https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/bbQb0/kvadratnoie-uravnieniie-2
# Квадратное уравнение - 2
# Даны произвольные действительные коэффициенты a, b, c.
# Решите уравнение ax²+bx+c=0.
def get_quadratic_equation_solution(a, b, c):
if a == 0:
if b != 0:
... |
6b5bd8d99294263e22b32e9e965bb88989389228 | QinmengLUAN/Daily_Python_Coding | /LC1219_getMaximumGold_Backtracking.py | 1,682 | 4.1875 | 4 | """
1219. Path with Maximum Gold
Medium: Backtracking
In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.
Return the maximum amount of gold you can collect under the conditions:
Every time you are located in a cell you will collect ... |
8adc475573705442312a86272f0b6d9e313f765f | socc-io/algostudy | /ProblemPool/sort_mergesort/becxer.py | 575 | 3.75 | 4 | def merge(P,Q):
ip = 0
iq = 0
res = []
while True:
if ip >= len(P) or iq >= len(Q):
break
if P[ip] > Q[iq]:
res.append(Q[iq])
iq += 1
elif P[ip] <= Q[iq]:
res.append(P[ip])
ip += 1
if ip < len(P):
res.extend(P[ip:])
if iq < len(Q):
res.extend(Q[iq:])
print str(P) + "+"+str(Q) + "=" +str... |
6dfcde2002de53d1017cf093ddec7866e1f6cfca | JeremyYao/LearningPython | /Chatper9Classes/die.py | 879 | 4.1875 | 4 | import random
# 9-13. Dice: Make a class Die with one attribute called sides , which has a default
# value of 6. Write a method called roll_die() that prints a random number
# between 1 and the number of sides the die has. Make a 6-sided die and roll it
# 10 times.
# Make a 10-sided die and a 20-sided die. Roll each d... |
57e0732f122637551f1fd9def4b981acb3d5d8ad | miaviles/Core-Python-From-Basics-to-Advanced | /Files/File Handling/fileName.py | 296 | 4.5 | 4 | # write python program to capture any filename from the keyboard
# and display its filename and extensions separately
fileName = input("Enter any filename: ")
print("You entered: ", fileName)
output = fileName.split(".")
print("File name : ", fileName)
print("Extension : ", output[1])
|
965bf2387cf195d03cc5a06cf88286c409e334bf | rocketpy/tricks | /zone_info.py | 1,018 | 3.625 | 4 | # zoneinfo — IANA time zone support
# Docs: https://docs.python.org/3/library/zoneinfo.html
from zoneinfo import ZoneInfo
from datetime import datetime, timedelta
dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
print(dt)
# 2020-10-31 12:00:00-07:00
dt.tzname()
# 'PDT'
dt_add = dt + timede... |
f2b90d99fa73d63b85d3c2ee98bbfb6b66a54577 | milu234/Python | /set.py | 619 | 4.03125 | 4 | my_set={1,2,3}
print(my_set)
my_set={1.0,"Hello",(1,2,3)}
print(my_set)
my_set={1,2,3,43,2}
print(my_set)
a={}
print(type(a))
a=set(a)
print(type(a))
#print(my_set[0]) #set does not supports indexing
my_set.add(12)
print(my_set)
my_set.update([56,45,89])
print(my_set)
my_set.discard(12)
print(my_set)
my_set.remove(45)
... |
9294b67ebda081cb812f85077bbbf7376b436428 | StrokeRehabilitationRobot/Main | /Robot.py | 2,632 | 3.546875 | 4 | from math import pi
import helper
class Robot(object):
"""
Robot class to hold state and description of the robot
"""
def __init__(self,arm="thanos",id=0):
"""
:type id: arm id
:param arm: which arm do you want
:param id: id of the arm
"""
self._name =... |
831be791c23794e8eea303fac1462c5b023825af | Amenable-C/Python_practice | /primeNumber+.py | 454 | 4.0625 | 4 | # Prime Number
while True:
num = int(input("Enter a value (-1 to quit): "))
if num == -1:
print("Bye")
break
elif num == 1:
print("Nope")
elif num == 2:
print("Yeees!!")
elif num > 2:
for i in range(2, num):
if num % i == 0:
print(... |
f632839e0d6bd3550d174674dcee725e5accc91c | YeSei/python3 | /day4/fib.py | 426 | 3.609375 | 4 | # Author:Jay
#斐波拉契函数
'''
生成器只有在调用时才会生成相应的数据
只记录当前位置
只有一个__next__()方法。next()
'''
def fib(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a + b #t=(b,a+b) , (a,b)=t
n= n + 1
return 'done'
f = fib(10)
print(f)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__nex... |
1f015c03669d0ff6eadb0fd5f7921a0edc6ebeff | shrikam/py-repo | /coomonInlist.py | 234 | 3.640625 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
f=[]
for i in range (0,len(a)):
for j in range (0,len(b)):
if a[i]==b[j]:
f.append(b[j])
break
print(f)
|
38c3451301943e3c3dab2ebbc12eb1d2a9c7164f | abhnvkmr/hackerRank | /sherlockbeast.py | 456 | 3.78125 | 4 | # Hackerrank - Algorithm - Warmup
# Sherlock and the Beast
def get_result(n):
fives, threes = 0, 0
for i in range(n, -1, -1):
if not (n - i) % 5 and not i % 3:
fives = i
threes = n - i
break
if fives == 0 and threes == 0:
print(-1)
else:
prin... |
a01572aa4eb23712a34425bf2c293005f7247ea3 | Takuma-Ikeda/other-LeetCode | /src/easy/test_make_two_arrays_equal_by_reversing_sub_arrays.py | 897 | 3.5 | 4 | import unittest
from answer.make_two_arrays_equal_by_reversing_sub_arrays import Solution
class TestSolution(unittest.TestCase):
def setUp(self):
self.target = [
[1, 2, 3, 4],
[7],
[1, 12],
[3, 7, 9],
[1, 1, 1, 1, 1],
]
self.arr ... |
74893bc767e9f9006919d052916825d2336c71a0 | Zenit95/GestorMp3 | /Repo.py | 1,645 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import sqlite3
def connectDB(dbFile):
conn = sqlite3.connect(dbFile)
cur = conn.cursor()
return conn,cur
conn, cur = connectDB("mp3DB.sqlite")
def addSong():
title = raw_input("\n\tIntroduzca el titulo\t")
author = raw_input("\n\tIntroduzca el autor\t")
time = raw_in... |
435d65b41d84662bee3b071b405ad5a496e453a8 | Jacob-TylerThomas/CSC-231-Labs | /Lab3/listing_2_8.py | 607 | 3.84375 | 4 | def anagramSolution4(s1,s2):
c1 = [0]*26
c2 = [0]*26
for i in range(len(s1)):
pos = ord(s1[i])-ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i])-ord('a')
c2[pos] = c2[pos] + 1
j = 0
stillOK = True
while j<26 and stillOK:... |
96421ea74c14bf9d0e6b3dad36cea3cafb86f76b | anidh/python-udemy | /lambda.py | 498 | 4.25 | 4 | #Using a normal function to calculate the square of a value
def suared(x):
return x**2
print(suared(23))
#This will print the square of a value by normal means i.e functions
#Now using anonymous functions here
#First define a lambda by keyword lambda
#Then use a variable
#Then use the expression which we want
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.