blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cefdb4cfb9c5f408b2383609401ac30d2e2428e9 | siumingdev/coding-exercises | /crokking the coding interview/9. Pattern Tree Depth First Search/Sum of Path Numbers (medium)/solution.py | 826 | 3.734375 | 4 | class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left, self.right = left, right
def find_sum_of_path_numbers(root):
def dfs(node, path_number, path_numbers_sum):
if node is None:
return path_numbers_sum
cur_path_number = path_number * 10 + node.val
if (... |
a4d09ca9709c514a94a4998a2441efde60819650 | radomirbrkovic/algorithms | /sort/insertion-sort/insertion-sort.py | 337 | 4.09375 | 4 | def InsertionSort(array):
for i in range(1, len(array)):
j = i - 1
nextElement = array[i]
while (array[j] > nextElement) and j >= 0:
array[j+1] = array[j]
j = j -1
array[j+1] = nextElement
return array
print InsertionSort([25, 21, 22, 24,... |
544de35f0ed7953824a0fb7606900225690b08b5 | KenOtis/Basic-Triangle-program | /Triangles.py | 1,469 | 4.25 | 4 | def Stars():
print("Star Triangle:")
a="*"
n=5
for i in range (0,n): ##handles the number of rows
for j in range(0,i+1): ##handles the number of columns
print (a,end="") ##prints the stars
print ("\r") ##ending each line after... |
8090ce93071f74490f2ee56bba364ed14926ca26 | lukexyz/Luketools-CV | /003_scrollbar_elements.py | 942 | 4.03125 | 4 | """
Scrollbar Elements
Creates a window with three scroll bars, each corresponding to an RGB value.
Slide the scroll bars to change the background colour.
"""
import cv2
import numpy as np
cv2.namedWindow('window')
# Create a variable with the fill colour for the image
fill_val = np.array([255, ... |
fa964910691f78ad91347a9830a600b2bf894258 | vansh1903/Python_Subs | /WebScrapingProject.py | 1,744 | 3.53125 | 4 | import requests
from bs4 import BeautifulSoup
import sqlite3
import pandas
def connect():
conn = sqlite3.connect("country.db")
conn.execute("CREATE TABLE IF NOT EXISTS COUNTRY_INFO (NAME TEXT, CAPITAL TEXT, POPULATION INT, AREA FLOAT)")
print("Table created successfully")
conn.close()
def insert_i... |
1c6fee3f7770f5cc98b109c8b2c50cef01e83738 | chausies/programming_tutorials | /data_structures_examples.py | 3,515 | 4.40625 | 4 | #-----------------#
# List examples #
#-----------------#
# Lists hold a bunch of objects in them, whether they be ints, strs,
# floats, or whatever.
l = [1, 2, 1, 3.14159, "pi", "anh"]
print "l = " + str(l)
# example of several useful list thingies:
# list length
print "length of l is " + str(len(l))
# index ... |
674e5a6ddc7fe050a84ff727c75234cc534160e3 | ve0377oa/Final-Project | /taco.py | 3,151 | 3.578125 | 4 | '''Mohamed Mohamed May 13, 2020 ITEC 1150 Final Project'''
# Use requests to download three random tacos from the random taco API.
# Save the data for each of three tacos in your program.
# Notice that each recipe is divided into five sections for
# base_layer,
# seasoning,
# mixin,
# condiment,
# and shell.
# Use ... |
446d59e50aa727025c35604660dda47d09c5c22c | otorugo/curso-python | /condicoes.py | 254 | 3.9375 | 4 |
#IF
if(1 == 1):
print('É igual')
# IF com ELSE
if(1 == 2):
print('É igual')
else:
print('É diferente')
#ELIF
a = 1
b = 2
if(a == b):
print('É igual')
elif(a > b):
print('a é maior que b')
else:
print('b é maior que a') |
aaa1039c58fc42e8fc1e62b14a9937139af98b21 | Platforuma/Beginner-s_Python_Codes | /12_oops/9_OOPS--getter-and-setter.py | 707 | 3.921875 | 4 | '''
For the above mentioned program, use getter method to get the
name and balance of the customer and setter method to set the
new name of the customer.
'''
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def credit(self, deposit):
... |
4d7bbb7a1b9d32cea3676c6c4484c21d74360285 | shreshta2000/list_questions | /same_digit.py | 186 | 3.59375 | 4 | list1=[2,4,6,8]
list2=[4,6,3,8]
if len(list1)<len(list2):
a=list1
elif len(list1)>len(list2):
a=list2
else:
a=list1
i=0
while i<len(a):
b=list1[i]
if b==list2[i]:
print(b)
i=i+1
|
8a2aadd4bc70e0817a70218edfc31191d1700fb1 | Helblindi/ProjectEuler | /21-40/Problem25.py | 2,057 | 4.0625 | 4 | """
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the inde... |
ba4b160533dafb06d1fc0b9179389bc505193ca6 | TheGreatCabbage/ParticlePy | /analysis/sample_get_data.py | 1,185 | 3.671875 | 4 | import data
from matplotlib import pyplot as plt
import sys
"""
This is a sample showing how to access data using the new data.py file.
"""
# Here's the Raspberry Pi data.
pi_data = data.get_pi_data()
# Another way to get the data. This method works for all datasets, just change the parameter.
pi_data = data.get... |
dcc41c2b3727014363802da3c3db7d17b7d927ec | Aasthaengg/IBMdataset | /Python_codes/p02831/s226012403.py | 122 | 3.640625 | 4 | def gcd(_a, _b):
if _a%_b==0:return _b
else:return gcd(_b, _a%_b)
A, B=map(int, input().split())
print(A*B//gcd(A, B))
|
f0b9bd3fa123a28bbed2f8563bccb0b00991a9ab | andjf/PlaneCalculator | /build_plane.py | 6,579 | 3.53125 | 4 | """
@author Andrew Ferrin
9.10.2020
"""
from tkinter import *
NUMBER_OF_POINTS = 3
DECIMAL_ERROR_TOLERANCE = 0.000001
ROUND_TO = 5
BACKGROUND = "#373832"
BUTTON = "#C1C4B3"
TEXT_AGAINST_BACKGROUND = 'white'
BUTTON_TEXT_COLOR = 'black'
ENTRY_FOREGROUND = 'black'
ENTRY_BACKGROUND = 'white'
# TEXT_INPUT ... |
122c92e72223f736e10b17bcc82b81ce0aedba33 | open-blockchain-explorer/Bank | /v1/utils/trust.py | 451 | 3.546875 | 4 | def calculate_weighted_trust(*, node, node_list):
"""Calculate the weighted trust (0-100) for the given node using the node_list"""
total_trust = sum([node.trust for node in node_list])
return (node.trust / total_trust) * 100
def decrease_trust(*, amount, node):
"""Decrease trust of the given node"""
... |
d9b5ae94151704f3e50faa0356c91cfa087e5b78 | MaysarahUlfah/groupk | /script.py | 1,229 | 3.953125 | 4 | from product_item import ProductItem
# Membuat daftar komoditas dan harganya
product_item1 = ProductItem('Beras Rojolele 5 kg', 56_000)
product_item2 = ProductItem('Gulaku 1 kg', 13_000)
product_item3 = ProductItem('Terigu Mila 1 kg', 11_000)
product_item4 = ProductItem('Minyak Goreng Filma 1 ltr', 18_000)
product_it... |
e777c1a1e199fefb2f6cdb4f11305ae21a30cd64 | KwangmyungLee/github_test | /Baekjoon Online Study/5.21.2021 practice.py | 7,247 | 4.09375 | 4 | ''' [Question 8958]
Question
There is an objective test result such as “OOXXOXXOOO”. An ‘O’ means a correct answer of a problem and an ‘X’ means a wrong answer. The score of each problem of this test is calculated by itself and its just previous consecutive ‘O’s only when the answer is correct. For example, the score ... |
cc1ffb3bcd889e88fbbe0b8d74addf380592265f | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/03 Complex_conditions/Invalid_number.py | 103 | 3.515625 | 4 | num = float(input())
in_range = (100 <= num <= 200) or num == 0
if not in_range:
print('invalid') |
3ce3b4fa674ec222ce3ec95a2aa6d786acc160eb | terrytangyuan/scaffolder | /inst/test_module.py | 418 | 3.609375 | 4 | def f1(a=3, type="linear"):
"""
Initialize the model.
Parameters
----------
a : int, optional
Description for a.
Defaults to 3.
type : str, optional
Type of algorithm (default: "linear")
"linear" - linear model
"nonlinear" - nonlinear model
Returns
------... |
6631eddb7fc0a31d6e6b1780056581b645dbedbb | syurskyi/Python_Topics | /065_serialization_and_deserialization/004_csv/_exercises/templates/The_Modern_Python_3_Bootcamp/Coding Exercise 100 print_users.py | 246 | 3.609375 | 4 | # Print Users CSV Solution
import csv
def print_users():
with open("users.csv") as csvfile:
csv_reader = csv.DictReader(csvfile)
for row in csv_reader:
print("{} {}".format(row['First Name'], row['Last Name']))
|
ed0f4e2c7b9b5c133379acb04fc3c35e06243c0a | rgj7/coding_challenges | /codeabb/Python/p52_pythagorean_theorem.py | 581 | 3.53125 | 4 | """
CodeAbbey, Problem 52
Coded by whoisrgj
"""
def triangle_type(a, b, c):
x, y = a**2 + b**2, c**2
if x > y:
return 'A'
elif x < y:
return 'O'
return 'R'
def main():
n = int(input())
# results = []
# for _ in range(n):
# a, b, c = map(int, input().split())
#... |
0ef35debe76183c83fcff2486cc0ddc58bc691fe | lemon-l/Online-Judge | /基础练习/字符串对比.py | 1,492 | 3.765625 | 4 | '''
Description
给定两个仅由大写字母或小写字母组成的字符串(长度介于1到10之间),它们之间的关系是以下4中情况之一:
1:两个字符串长度不等。比如 Beijing 和 Hebei
2:两个字符串不仅长度相等,而且相应位置上的字符完全一致(区分大小写),比如 Beijing 和 Beijing
3:两个字符串长度相等,相应位置上的字符仅在不区分大小写的前提下才能达到完全一致(也就是说,它并不满足情况2)。比如 beijing 和 BEIjing
4:两个字符串长度相等,但是即使是不区分大小写也不能使这两个字符串一致。比如 Beijing 和 Nanjing
编程判断输入的两个字符串之间的关系属... |
fd4378ea514c2d71df21020dcb91e57b3c54b9fa | ashwingur/Acorn | /test_player.py | 1,509 | 3.75 | 4 | from game import Game
# The player class requires a game object to be created, in order to properly test on a grid
# The game_move function runs the player move function
# Positive test case to check if moves and picking up buckets is working
def test_player_position_and_buckets():
game_object = Game('board_medium... |
de36c9d1982d6272dd1b2b4ca125f5b860908a62 | mail-vishalgarg/pythonTest | /TestPython/PyScripts/reverseinteger.py | 371 | 3.703125 | 4 | number = int(input())
numberlist = []
for i in range(number):
numberlist.append(input())
print numberlist
length = len(numberlist)
last = length -1
for i in range(length/2):
numberlist[i],numberlist[length-i-1] = numberlist[length-i-1],numberlist[i]
print numberlist
str_arr = raw_input()
... |
57ed657564a0497df05ac446577d29eddab2dc39 | sunshinewxz/leetcode | /57-insert.py | 2,158 | 3.578125 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[... |
8885c9bba5fd37e67024d3a704771cca21ac3c53 | ZandroWallaert/Python-Exercises | /sessions/session03_iteration/assignment04_star_square.py | 430 | 4.4375 | 4 | """
# Star Square
Write a program that asks for two numerical inputs (``int``): the height and the width of a rectangle.
Print such a rectangle on screen using ``*``.
The program has no output if either the height or the width is negative.
## Example:
> 4
> 3
***
***
***
***
"""
height = int(... |
881fb6495a14b7ae760e0a54e307ff36736e749d | jonmcalder/exercism-solutions | /python/atbash-cipher/atbash_cipher.py | 506 | 3.9375 | 4 | def encode(string):
"""
Encrypt text using atbash cipher
"""
encoded = transform(string)
encoded_blocks = ' '.join(encoded[i:i+5] for i in range(0, len(encoded), 5))
return encoded_blocks
def decode(string):
"""
Encrypt text using atbash cipher
"""
return transform(string)
def transform(raw_stri... |
2aff8fd320b56cccc06159adcc44a9cd562ff394 | oilmcut2019/final-assign | /jupyter-u07157127/Quiz_Python_20190309.git/Quiz_4.py | 144 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
a=int(input())
b=int(input())
for z in range(a,b+1):
print(z);
z=z+1;
# In[ ]:
|
f5d9814586025a2d8bf61ee63245af175a4b97ac | alifsyr/Willy-Wangky-System | /F04_login.py | 1,322 | 3.640625 | 4 | def login(user_data):
import B01_hash
#inisialisasi belum berhasil
paswValid = False
#input username dan password
uname = input('Masukkan username: ')
pasw = input('Masukkan password: ')
#array dummy yang sama seperi di main
dummy = [" $NOUSER",... |
2c92b781cbb7a7905ffbf4b4a4bc5db1f0686d1a | yehongyu/acode | /2019/sort/sort_colors_148.py | 1,866 | 3.625 | 4 | class Solution:
"""
@param nums: A list of integer which is 0, 1 or 2
@return: nothing
"""
def swap(self, nums, i, j):
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
def helper(self, nums, l, r, k):
if l == r and k == 1:
return nums[l]
if l + ... |
cfec87a0b21cd43b2f3cd50884c01f1ad3b035d2 | cculver81/codingdojo_dailyalgos | /coin_change.py | 804 | 3.890625 | 4 | # Let's revisit Generate Coin Change
# Change is inevitable (especially when breaking a twenty). Make generateCoinChange (cents). Accept a number of American cents, compute and represent that amount with the smallest number of coins. Common American coins are pennies (1 cent)
#Given 33
def generateCoinChange(num):
... |
19f8719fcb135da11f9745c324a6da5683761126 | zdravkob98/Programming-Basics-with-Python-March-2020 | /Programing Basics March2020/1/Exam Preparation.py | 265 | 3.625 | 4 | income = float(input())
count_mouth = int(input())
costs = float(input())
another_costs = income * 0.3
saving = income - costs - another_costs
total_saving = count_mouth * saving
print(f"She can save {(saving / income) * 100:.2f}%")
print(f"{total_saving:.2f}")
|
9431b282f3f3804bdc0ce6773eb5e0477de5123a | ChristopherHubbard/news-stock-predictor | /src/server/Prediction/PrintLayer.py | 631 | 3.5 | 4 | import torch
# Layer to print the intermediate Tensor in hidden layersz -- used as a helper
class PrintLayer(torch.nn.Module):
def __init__(self, printSize=False):
# Call the base constructor
super(PrintLayer, self).__init__()
# Setting to print the size or not
self.printSize = p... |
0dc1232d803eabbb18a2049bcd9d2012be0803a1 | SenthilKumar009/100DaysOfCode-DataScience | /Python/Concepts/Exception/exceptionCheck.py | 811 | 4 | 4 | def ask_for_int():
while True:
try:
result = int(input('Enter the number:'))
except:
print('You have entered the non-integer value!!!')
continue
else:
print('You have entered: ', result)
break
finally:
print('En... |
a36aa6103070c897d2fb82c5ddf27e6c5f1cafc5 | ebmeurer/algebra-linear | /prova3.py | 3,008 | 3.921875 | 4 | import math
from math import sqrt
num_elementos = 0
num_vetores = 0
def get_produto_interno():
global num_elementos
num_elementos = int(input("Quantos elementos existem nos vetores de A? "))
A = []
for i in range(2):
A.append([])
for j in range(num_elementos):
A[i].append(f... |
438b93b0c0fc10372822038ad499da620a5d51e8 | MaxPoon/Leetcode | /python/329.LongestIncreasingPathInAMatrix.py | 860 | 3.53125 | 4 | def dfs(matrix, longest, rows, cols, row, col):
if longest[row][col]!=0: return
longest[row][col] = 1
for (r,c) in ((row+1, col), (row-1,col), (row,col+1),(row,col-1)):
if r<0 or r>=rows or c<0 or c>=cols or matrix[row][col]>=matrix[r][c]: continue
if longest[r][c] == 0: dfs(matrix, longest, rows, cols, r, c)
... |
93f75d20a2c98a2a401436f3b7f772193e11e00d | lucisun/git_chk_daysToDate | /pyDateChk.py | 2,024 | 3.546875 | 4 | #!/usr/bin/python3
import datetime
from datetime import date
###################################################
# read from file of dates/description
# and determine how many days until that day
###################################################
def check_upcoming():
date_file = open("../apptfile.txt",'r')
... |
87f584ee24751f3f5f47f3838d9057605535b518 | ItzelMM/first-repository | /HW4/ZyLb4.py | 887 | 3.65625 | 4 | # Itzel Munoz Monroy PSID: 188446
def partition(list_v, lowest, highest):
pivot = list_v[highest]
check = lowest - 1
for x in range(lowest, highest):
if list_v[x] < pivot:
check += 1
holder = list_v[x]
list_v[x] = list_v[check]
list_v[check] =... |
4c39349562fad790a336e6479f375ec4d3b37a50 | lambdaplus/python | /Algorithm/sort/insert_sort.py | 396 | 3.59375 | 4 | # coding=utf-8
from random import randrange
def insert_sort(L):
if len(L) < 2:
return L
for i in range(1, len(L)):
tmp = L[i]
j = i - 1
while j >= 0 and L[j] > tmp:
L[j + 1] = L[j]
j -= 1
L[j + 1] = tmp
return L
# if __name__ == '__main__... |
11d2bdf41ecdb971900cae490bf3d28a785aa85a | Ran4/condict | /condict/__init__.py | 562 | 4.0625 | 4 | #!/usr/bin/env python3
from typing import Dict, Any
def when(x: Any, d: Dict) -> Dict:
"""
Used to build conditional dicts.
Usage:
>>> some_dict = {
... "some_mandatory_value": "OK",
... **when(hasattr(user, id), {
... "user_id": user.id,
... })
... }
... |
e305cb7d8f62fedf79181e57e5fbaeb5437e58d0 | aleksandra-asanin/NordVPN_Randomizer | /NordVPN_Randomizer.py | 3,271 | 3.53125 | 4 | #!/usr/bin/env python3
import subprocess, re, random, datetime
def statusCheck():
"""
This function will run a status check on your nordvpn service to see if you are already connected. You must be disconnected for this program to work.
"""
nord_output = subprocess.Popen(["nordvpn", "status"], stdout... |
6819ff4a69781e7dcee1d8af27965b7439ff662d | paularah/Data-Structures-Algorithms | /Arrays/static_array.py | 3,282 | 4.09375 | 4 | """
A Static Array Abstract Data Type Implementation
Implementations Decisions:
This mimics the implementation of python's list except that they are static
The size of the array is predefined to be of 10
This ADT uses zero based indexing
"""
class Array:
def __init__(self, *initial_value):
"""
T... |
37d03e7b648e19ba5f0458e66802ee8f406cb0f3 | mjuchno/my-first-roguelike | /map_shift_test.py | 1,166 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 22 09:10:16 2019
@author: mjuchno
"""
class Tile:
"""
A tile on a map. It may or may not be blocked, and may or may not block sight.
"""
def __init__(self, blocked, block_sight=None):
self.blocked = blocked
# By defa... |
a985f51aa43cb414d92ac825f6523b3908a8fc43 | russell13192/Python-R_ML_Models | /Documents/python_machine_learning/data_preprocessing_final.py | 518 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 18 21:05:05 2018
@author: Russell Murray
"""
# Importing the Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
# Spli... |
48ce65e046aa7409b3d1ffff373c54535de44ec8 | brlala/Educative-Grokking-Coding-Exercise | /Leetcode/295. Find Median from Data Stream.py | 1,457 | 3.765625 | 4 | class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.max_heap = [] # to contain left smaller half, or + 1
self.min_heap = [] # to contain right bigger half
def addNum(self, num: int) -> None:
if not self.max_heap or -self.m... |
0a2f908337e9ea5f3103f4b5873a52b73c4edb10 | ssthakur555/Data-structure-and-Algorithm-DSA- | /l Linear Search.py | 221 | 3.828125 | 4 | def binarySearch(array, target):
for i in range(len(array)):
if target==array[i]:
return(target,"is in index number",i)
else:
return('''it
is not the part of our list ''')
break
|
bf3ea6048172a67bc93dd5e22cb9810a3590f1d8 | coder-flag/algorithm | /test5.py | 1,920 | 3.515625 | 4 | # 以二叉树对应的完全二叉树为参照,空白节点处使用#字符填充,使用层次遍历表示二叉树,节点间使用空格分割,如4 2 7 # 3 6 9,
# 输出其镜像
"""
way1 暴力美学
1.空白节点用#填充,因此可以把它当作完全二叉树
2.完全二叉树除叶节点所在层外,每层节点数满足2**n,n是所在高度高度减1,
如第一层有2**0个节点,第二层有2**1个节点
3.计算层数
sum = 0 ,i = 0
循环:last_sun = sum ,sum += 2**i, i += 1
退出循环: sum >= length
则树的高度为 height = i,叶节点数: leaf_nodes = ... |
1a02bddb90a2d1dd3508a3c751caad6765bc515d | marko-knoebl/courses-code | /python/2018-11-participant1/text_test.py | 242 | 3.5 | 4 | file = open("message.txt", "w", encoding="utf-8")
file.write("hello world! error error error")
file.close()
file = open("message.txt", "r", encoding="utf-8")
content = file.read()
errorcount = content.count("error")
print(str(errorcount)) |
32735a70c4d7a3f1f75227b000759ba776cd00d8 | s991116/robot-projects | /Raspberry/Python/Sandbox/readkey.py | 377 | 3.53125 | 4 | #! /usr/bin/python
import curses
screen = curses.initscr()
try:
curses.noecho()
#curses.curs_set(0)
screen.keypad(1)
screen.addstr("Press a key")
event = screen.getch()
finally:
curses.endwin()
if event == curses.KEY_LEFT:
print("Left Arrow Key pressed")
elif event == curses.KEY_RIGHT:
... |
8c4b53db5adc476bbecd85d386097a5620f33795 | andrewboychurch/two-envelopes | /TwoEnvelope_Play_All_Hands_Tuples_version.py | 4,903 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 4 08:30:37 2017
@author: Andrew
TWO ENVELOPE GAME: INITIAL ENVELOPE VALUES FROM 1 TO 100
Generates sample space of 400 envelope pairs and
each round a random selected pair's values are
appended to appropriate STAY and SWAP lists
E1 values even distribution ... |
3e2c47dd5e82e7827277b39cd10d9e4138590306 | adamnemecek/biomedicalSignalProcessing | /exploration/python/spiningStick.py | 1,330 | 4.03125 | 4 | """
Course: Quaternion Wavelets in Medical signal processing
Example1_From Fourier series to Fourier transform
Description:
This example that shows how the fourier series exentends
its applicability for infinte periodic signals.
@autor ArielIporre
"""
import numpy as np
from numpy import sqrt
import matplotlib.pyplo... |
1e7dac322394efd18d2b5c077698ada15edf5c05 | meghalrag/pythonExample | /commonPgm/diagonal.py | 456 | 4.1875 | 4 | n=input("enter the order:")
mat=[]
for i in range(n):
r=[]
for j in range(n):
x=input()
r.append(x)
mat.append(r)
for i in range(n):
print mat[i],""
for i in range(n):
for j in range(i+1,n):
if i==j:
continue
elif(mat[i][j]<mat[j][i]):
... |
84286532df33edf7300058ba8ba2d2c6d86f50c1 | isabellahenriques/Python_Estudos | /ex078.py | 935 | 3.984375 | 4 | ''' Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
No final, mostre qual foi o maior e o menor valor digitado e
as suas respectivas posições na lista.'''
valores = []
maior = 0
menor = 0
for contador in range(0, 5):
valores.append(int(input(f'Digite um valor para a Posição {contador}: ')))
... |
9ef767ca04140f2d69cbca44120ecd76dc085846 | RaglandCodes/Algos | /Add to Array-Form of Integer.py | 313 | 3.53125 | 4 | '''
LeetCode 989. Add to Array-Form of Integer
https://leetcode.com/problems/add-to-array-form-of-integer/
'''
class Solution:
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
A = int("".join(str(i) for i in A))
return [int(i) for i in list(str(A + K))]
|
6017c06a6bb38a2aee650c546a7f6d1cf42b99e4 | xorkevin/CodeWarsHP2016 | /prob03.py3 | 375 | 3.546875 | 4 | import sys
def hasDouble(word):
letters = list(set(list(word)))
if len(''.join(letters)) < len(word):
return True
return False
f = sys.stdin.read()
f = f.split('\n')
skip = False
for line in f:
if skip:
if hasDouble(line):
print('likes ' + line)
else:
... |
5f7ffc48fed4f60318cf6a24b8d81943aa99a1bf | Phoebectw/D002-2019 | /L2/q3.py | 173 | 3.578125 | 4 | y=0
b=-999
n= [-120, 14, 93, 320, 1, -999]
print n
while y<6:
for N in n:
if N>b:
b=N
y=y+1
print ("the largest number is"),( b)
|
dc46a5a5d074e1e6d9f0d7979048e5162ea31d6d | vasivaas/Python_task | /move_zero_to_end.py | 631 | 3.546875 | 4 | #0
def move_zero_to_end(l):
for index in range(len(l) - 1):
for el in range(len(l) - 1 - index):
print l
if(l[el] == 0 and l[el+1] != 0):
l[el], l[el+1] = l[el+1], l[el]
return l
print move_zero_to_end([0,1, 0,0,3,1,2])
print move_zero_to_end([10,1,0,3,1,0,0,0,2])
#1
def python_helpers(nums):
pos = 0... |
d0eebacd889d94942cf2671115225ce0d544bc14 | jonathanlam/permsandcombs | /perms.py | 1,135 | 4.0625 | 4 | from itertools import *
def subword_from_word(word, length=None):
""" Answers a question of the form 'How
many ways can you form a _length_ letter
word from _word_
The function returns a list of these words
"""
length = len(word) if length is None else length
a = {''.join(p) for p in permut... |
d5f106d3007e2fcad09562321650494c41ac447c | tchaitanya2288/python_project | /while_ex1.py | 128 | 3.828125 | 4 | #!/usr/bin/python
l = []
num = 0
while num <10:
print("the value of num is :", num)
num += 1
l.append(num)
print(l) |
abb71987fa53c899c89c795cbea6e89a9c8d1234 | to-besomeone/algorithm | /181011 - 2920.py | 222 | 3.640625 | 4 |
mel = list(map(int, input().split()))
melstr = ""
for i in range(8):
melstr += str(mel[i])
if melstr == '12345678':
print("ascending")
elif melstr == '87654321':
print("descending")
else:
print("mixed") |
8f320dec911db3427dd069483839e723cae8e3d9 | haiou90/aid_python_core | /day11/homework_personal/03_homework.py | 425 | 3.5625 | 4 | """
5. list01 = [6,2,3,4,5,6,7,3,2,4,8]
定义函数,删除列表中重复元素.(不使用其他容器,自定义算法)
"""
def delete_repetion(list_target):
for r in range(len(list_target)-1,0,-1):
for c in range(r):
if list_target[r] == list_target[c]:
del list_target[r]
break
list01 = [6, 2, 3, 4, 5, ... |
1a8c5769b702ec8f0ff3d9a9635778c963fa452f | colbydarrah/cis_202_book_examples | /CH7_min_max_method_with_list.py | 497 | 4.46875 | 4 | # Colby Darrah
# 3/23/2021
# 'min'/'max' method pg 381
# demonstrates how to identify lowest and highest values in list.
def main():
# Create a list.
list_numbers = [1, 2, 3, 4, 5]
# Display element/item with lowest value in sequence/list
print('The lowest value is', min(list_numbers))
... |
86f5b44f5e5d53a07cb92ac1202074f9299c7c14 | elevenmunki/guessing-game | /game_adv.py | 1,220 | 4 | 4 | """A more sophisticated number-guessing game."""
from random import randint
best_score = 99999
print "Howdy, what's your name?"
name = raw_input("(type in your name) ")
while True:
number = randint(1, 100)
tries = 0
print "{}, I'm thinking of a number between 1 and 100.".format(name)
print "Can you... |
08b3c0a3252a7c163635a63b9291d71b40458622 | ferromauro/python3_dojo | /Modulo_3/lezione_3_11.py | 301 | 3.71875 | 4 | #!/usr/bin/python
# SINTASSI Ternary Operator IN JAVASCRIPT [Condition] ? [Valore se True] : [Valore se False]
# SINTASSI Ternary Operator IN PYTHON [Valore se True] if [Condizione] else [Valore se False]
# Stampa A se la condizione è vera altrimenti stampa B
print('A') if 1 == 0 else print('B') |
eebfed095535ce70db54cd43e519c23a0115ce41 | MadsPoder/advent-of-code | /2022/day1.py | 882 | 3.59375 | 4 | from heapq import heapify, nlargest
from itertools import groupby
from functools import reduce
with open ('day1.txt') as fp:
calories_input = [x.strip("\n") for x in fp.readlines()]
# Group into list of lists - list for each elf
calories_per_elf = [
list(
[int(calorie) for calorie in calories_for_elf... |
ccb08a215261a4c6a1d95e21b99b6c7a06a979b0 | sagarprasad007/sagar-prasad | /swapping.py | 318 | 3.890625 | 4 | ##a=input("Enter 1st numbers :")
##b=input("Enter 2nd number :")
##print("before swapping :",a,b)
##c=a
##a=b
##b=c
##print("after swapping :",a,b)
##
##a=input("Enter 1st numbers :")
##b=input("Enter 2nd number :")
##a,b=b, a
##print("After swapping :",a,b)
name="Sagar"
del name
print(name)
|
578c4bc5f64facf7141a0bb5bffe235e17d49376 | cloeffler745/back-up | /code/test/ditance_func/test_alg.py | 1,183 | 3.875 | 4 | import Levenshtein
import numpy as np
import random
import string
import sys
first = sys.argv[1]
second = sys.argv[2]
## Algorithm -------------------------------------------------------------------
def edit_distance(s, t):
"""Edit distance of strings s and t. O(len(s) * len(t)). Prime example of a
dynamic... |
fa137784023f8277cd7064b0cd1f978a3bf3772c | IdeasLabUT/CHIP-Network-Model | /plotting_utils.py | 2,144 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Makan Arastuie
"""
import numpy as np
import matplotlib.pyplot as plt
def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", color_bar_format='%.1e',
grid_color='#e7dadb', font_size=20, **kwargs):
"""
Based on https://matplotlib.org/3.1.1... |
c84e8d08520a05946d32a1d5c7f7e4acbb174a38 | mzmudziak/Programowanie-wysokiego-poziomu | /zajecia_2/zadanie_1.py | 133 | 3.8125 | 4 | def makeTuple(sentence):
return [(word, len(word)) for word in sentence.split()]
print makeTuple('Ala ma kota a kot nie ma Ali') |
425c62c45e98a8714115adeb78b447824b788ef1 | cadets/dif-simulator | /parsing.py | 2,120 | 3.84375 | 4 | import itertools
def decode(opcode, operands, encoding, src):
"""
Decode operands for a specific opcode (e.g., ['MOV', '4', '2', '3']) into
a dictionary of named operands (e.g., {'rs1': 4, 'rs2': 2, 'rd': 3}).
"""
operand_names = list(encoding.operand_names())
# Are there enough operands?
... |
48dfa8a916662df283188d627f55fd1880b059f2 | zaoyuaner/Learning-materials | /python1901/1_python基础/day11/6.下划线.py | 652 | 3.734375 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# author:zhangjiao
'''
1.前后双下划线 比如__func__,一般是系统定义的函数或者变量
2.首双下划线 __func ,代表私有化的,不能直接访问。
3.首单下划线 _func,代表保护类型的,虽然它可以直接被访问,
但是请把它视为私有变量,不要直接访问。
'''
class Person:
__slots__ = ("name","__age__","_money")
def __init__(self,name,age,money):
self.name =name
... |
fbc67ad83ab9272a7d51bb07cfba2349dbdbbc94 | isabel-lombardi/workbook_python | /chap_3/ex-66.py | 845 | 4.1875 | 4 | # Compute a Grade Point Average
grades = []
while True:
grade = input("Enter an American grade: ").upper()
points = 0
if grade == "":
break
if grade == "A+":
points = 4.0
if grade == "A":
points = 4.0
if grade == "A-":
points = 3.7
if grade == "B+":
... |
634a43295b70abf4e34fc8601db54c8fd8e5cddd | imclab/iMoCap | /script/smplmodel/geometry.py | 11,704 | 3.5625 | 4 | import torch
import numpy as np
def rotation_matrix_to_angle_axis(rotation_matrix):
"""Convert 3x4 rotation matrix to Rodrigues vector
Args:
rotation_matrix (Tensor): rotation matrix.
Returns:
Tensor: Rodrigues vector transformation.
Shape:
- Input: :math:`(N, 3, 4)`
... |
5035dffcbdb92225606c4381de0395082da73b00 | DevZeyad/ds | /BankNotes.py | 480 | 3.984375 | 4 | #This is an uri online judge problem solution
#you have to read int value and calculate the smallest possible number of bank notes in which the value may be decomposed
#Actually , loved this idea :D
#So i decided to post my solution as a first github code for me
availableNotas = [100.00,50.00,20.00,10.00,5.00,2.0... |
d62ea9508adeb4efcbca8dd718168d0edcefbed1 | congxinxu0116/CMU15112 | /Week 3/week3/hw3.py | 14,486 | 3.703125 | 4 | #################################################
# hw3.py
#
# Your name:
# Your andrew id:
#################################################
import cs112_f19_week3_linter
import math
from tkinter import *
#################################################
# Helper functions
###########################################... |
7c042241329ce5ed78eb278d08010dc87306aca5 | mrsarthak001/Python | /PYTHON CODE/keyword.py | 202 | 3.765625 | 4 | print(5 > 6)
print(4 in [1,2,3])
print("hello" is "hello")
print(5 == 6)
print(5 == 6 or 6 == 7)
print(5 == 6 and 6 == 7)
print("hello" is not "hello")
print(not(5 == 5))
print(3 not in [1,2,3]) |
adb29f4e00abdeeda796ebc8c1676a25151431de | SniperBuddy101/learno | /Data Structure - Exercise.py | 701 | 3.6875 | 4 | org_sentence = "This is a common interview question"
sentence = org_sentence.upper()
print(sentence)
my_list_count = []
for x in sentence:
if x != " ":
my_list_count.append(sentence.count(x))
max_count = (max(my_list_count))
index_max = (my_list_count.index(max_count))
print(org_sentence[index_max])
# tha... |
31fff35a0674fa460e3893cb53b52b26ecbac722 | DanterM/Graduation-design | /学习过程/3、调用其他方法LM-GBM-SVM法计算RMSE、MAE、MAPE%/线性回归/index.py | 3,232 | 4.28125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: swensun
@github:https://github.com/yunshuipiao
@software: python
@file: KNN.py
@desc:线性回归:梯度下降
@hint:
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def init_data():
data = np.loadtxt('data.csv',... |
a2cc5f4026c425c8a34d5ebbc6fd839f4749b5fe | YuliaAzarova/310321 | /main.py | 186 | 3.65625 | 4 | import sys
sys.setrecursionlimit(10**9)
def f(n):
if n == 0:
return 1
else:
return n * f(n-1)# рекуррентное соотношение
print(f(10 ** 4)) |
f894b4a34ca835e7ded6a1237339340738ed242b | apurvasharma25/a1 | /record.py | 887 | 4.09375 | 4 | print("DMC")
x=input("Enter Student Name ")
print("Enter Your Subjects And Marks Below")
a=input("Subject= ")
b=input("Marks= ")
c=input("Subject= ")
d=input("Marks= ")
e=input("Subject= ")
f=input("Marks= ")
g=input("Subject= ")
h=input("Marks= ")
i=input("subject= ")
j=input("Marks= ")
Marks1=int(b)
Marks2=int(d)
Mar... |
d8a59000a8412631140de0275180beadb8ff77f2 | Maryamx21/INF101 | /TP9/traduc3.py | 462 | 3.671875 | 4 | fr = {"salut":"hey", "tu":"you", "il":"he", "bien":"great"}
def init_scores():
i = 0
dico = {}
nbr = int(input("Combien de joueurs total ? "))
while(i < nbr):
nom = input("Nom du joueur ? ")
dico[nom] = ""
i += 1
return dico
init_scores()
def jeu(dico_scores, dico):
i ... |
ddb3ae90614765c26575c41a37be0d3bd4d64e34 | is-already-taken/py-jira-cli | /printer_test.py | 5,831 | 3.90625 | 4 |
import unittest
import printer
class PrinterTest(unittest.TestCase):
"""It should print the expected one column text"""
def test_one_column(self):
s = printer._align([("XYZ", 20)], width=80)
self.assertEqual(len(s), 3, "overall width")
self.assertEqual(s, "XYZ", "correct output")
"""It should print the ex... |
ec8c9266349a84ac24ea0dfd0efa0fddb3337375 | SimplyClueless/DigitalSolutions2020 | /Classwork/testProjects.py | 489 | 4.21875 | 4 | num1Entered = False
num2Entered = False
if not num1Entered or not num2Entered:
while not num1Entered:
try:
num1 = int(input("Enter first number: "))
except:
print("Invalid Variable!")
else:
num1Entered = True
while not num2Entered:
try:
... |
a84ee4e032ef9328938a9c6fa3ed7e21c8c4b653 | dineshkarsid/dl-zoo | /deep-learning-with-pytorch/tutorials_scripts/nn_pytorch_simple.py | 1,152 | 3.625 | 4 | """
Fitting a random data using fully connected network with one hidden layer.
"""
import torch
dtype = torch.float
device = torch.device('gpu:0' if torch.cuda.is_available() else 'cpu')
# Define dimensions
N, D_IN, H, D_OUT = 64, 1000, 100, 10
# Create random data
X = torch.randn(N, D_IN, device=device, dtype=dt... |
e68b82298fea48faae38b457f69dbc6b1eef126a | TheDuckGoesQuark/UCIOT | /submission/old/ilnpsocket/underlay/routing/forwardingtable.py | 4,365 | 3.578125 | 4 | import logging
from typing import Dict, List
class ForwardingEntry:
"""
A record of the cost of a route via the next hop
"""
def __init__(self, next_hop_locator: int, cost: int):
self.cost: int = cost
self.next_hop_locator: int = next_hop_locator
self.left_to_live: int = 10
... |
376bc8279c183179efbec96f5c53a178a4ee763e | leticiafelix/python-exercicios | /08 - Repetições (while)/desafio057.py | 452 | 3.671875 | 4 | #crie um programa que leia o sexo de uma pessoa mas só aceite M ou F
#caso esteja errado peça a digitação novamente até obter um sexo valido
print('{:=^50}'.format(' LEITOR DE SEXO '))
sexo = str(input('Insira seu sexo [M/F]: ')).upper().strip()
while sexo != 'M' and sexo != 'F':
sexo = str(input('\033[31mPor fa... |
e81550d1f63738186f04e58a7707ec3f67aebe11 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_166/Bimestral1_166_20192/felipe craveiro portela/questao_4.py | 268 | 3.59375 | 4 | def programa():
base_triangulo = int(input('base do triangulo: '))
altura_triangulo = int(input('altura do triangulo: '))
area_triangulo = (base_triangulo * altura_triangulo)/2
print('area do triangulo e',area_triangulo)
programa()
|
e723b336f1adc0d941353b1dfcb677b667998c2c | DarioCozzuto/python-dates | /python dates.py | 489 | 4.125 | 4 | #Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
#Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
#Create a date object:
import datetime
x = datet... |
1634cfa0de01ee3ed38e7adb5924477c3c4ec026 | kojobobo/100days | /main.py | 551 | 3.5 | 4 | with open('Input/Letters/starting_letter.txt', 'r') as letter:
initial_letter = letter.read()
with open("Input/Names/invited_names.txt", 'r') as names:
initial_name_list = names.readlines()
final_name_list = []
for name in initial_name_list:
name = name.replace('\n', '')
final_name_list.append(name)
... |
1dc1d277e96342d9d3946b422c334e3efe1814e2 | opengate-io/python-service | /utilities.py | 393 | 3.53125 | 4 | def initRouteWithPrefix(route_function, prefix='', mask='{0}{1}'):
'''
Defines a new route function with a prefix.
The mask argument is a `format string` formatted with, in that order:
prefix, route
'''
def newroute(route, *args, **kwargs):
'''New function to prefix the route'''
return route... |
b91f18ed8f4b41b2f2955003a97b43079837f20f | bhavya2403/Learning-Python | /HackerrankSolutions/30-D code(python)/conditional_statements.py | 160 | 3.75 | 4 | N = int(input())
if int(N) == 2 or int(N) == 4 :
print('Not Weird')
elif int(N) % 2 == 0 and N > 20:
print('Not Weird')
else:
print('Weird') |
c21695cc36c77f76e4968de7ba3ceb2f21994899 | rohitkhatana/python_toy_scripts | /signup.py | 589 | 3.71875 | 4 | import re
usname=input('enter ur usname:')
passw1=input('enter password->')
passw2=input('varify password->')
user_re=re.compile(r"^[a-zA-z0-9_-]{3,20}$")
def valid_username(usname):
return user_re.match(usname)
user_pass=re.compile(r"^.{6,20}$")
def valid_pass(passw1):
return user_pass.match(passw1)
ch1... |
18c84195d050c33ab37764018247b61b3ed2794f | FG1996/Portfolio | /SumEvenSquare.py | 222 | 4.1875 | 4 | def sum_even_square(numbers):
#function sums the square of all even numbers passed into function.
sum_square=0
for num in numbers:
if num%2==0:
sum_square+=num**2
return sum_square |
4b818d17583c8b01fff7e905099c3f20f9d1249a | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/2459.py | 1,026 | 3.59375 | 4 | import sys
def flip(pancakes, start_index, number):
for i in range(start_index, start_index + number):
if pancakes[i] == '-': pancakes[i] = '+'
else: pancakes[i] = '-'
return 1
def pancake_flipper(pancakes, k):
flip_count = 0
for i in range(0, len(pancakes) - k + 1):
... |
495d5e5cbf9b2c66d7734f4f72f364b7a2b81268 | Blanco-Lucas/Aulas_Curso_em_Video-Python-1- | /nw001.py | 251 | 3.96875 | 4 | # Soma númerica
print('AUTO SOMA')
primeiro_valor = int(input('Qual primeiro termo: '))
segundo_valor = int(input('Escolha mais um termo: '))
S = primeiro_valor + segundo_valor
print(f'A soma entre, {primeiro_valor} e {segundo_valor} é {S}!')
|
de1ac4d6616d2d6f3c5dddaccfe23310dfc49994 | tommbarton/5-problems-for-every-coder | /Problem 4/sortList.py | 350 | 3.859375 | 4 | ## Write a function that given a list of
## non negative integers, arranges them
## such that they form the largest possible
## number. For example, given [50, 2, 1, 9],
## the largest formed number is 95021.
listX=[50,2,1,9]
sortedListX = sorted(map(str, listX), cmp=lambda x1,x2: cmp(x1+x2, x2+x1), reverse=True)
pr... |
068507e289b0b0e328f19efccf33cad071651d99 | GovorunV/class | /class.py | 2,199 | 4.09375 | 4 | '''class User:
name=""
srname=""
age=""
email=""
def set(self,name,srname,age): #self обезательный
self.name=name
self.srname=srname
self.age=age
def printall(self):
print("Пользователь",self.name,"его возраст",self.age)
admin=User()
admin.set("Admin","Marg","23... |
6470ff97e26c5500bcc71e1ce102b71035803b53 | antalcides/python | /source/no_se.py | 504 | 3.859375 | 4 | # 1. Que hace esta funcion?
# 2. Como funciona?
# 3. Rastree el programa insertando instrucciones
# print para observar el contenido de las variables
# durante la ejecucion.
def no_se(n):
# n debe ser un entero positivo
if n<1 or n==1:
return []
lista = [2]
for i in range(3,n+1):
... |
d27259238cef53483424d2738b0f7b24146429f7 | pleiby/algorithms_course | /Course3_Algs_on_Graphs/week6_adv/Advanced-Shortest-Paths/dist_with_coords/graph_types.py | 641 | 3.515625 | 4 | #!/usr/bin/python3
# graph_types.py
#=============================================
# python Type Aliases
# Edge is a connection between two vertices
class Edge:
# Source Vertex
# Destination Vertex
# Weight float64
pass # an empty class that can be used as a struct
from typing import NewType
User... |
0c033e46a57fb9812713806785697403491300eb | Maralex1592/Documentation-courses | /Curso de Python/data strucuture/ahorcado.py | 2,282 | 4.0625 | 4 | # -*- coding: utf-8 -*-
import random
IMAGES = ['''
+---+
| |
|
|
|
|
|
=======''','''
+---+
| |
O |
|
|
|
|
=======''','''
+---+
| |
O |
| |
|
|
|
=======''',''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.