blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f4f309ec92fa0e71675d0d184b576b84483a1b56 | wbddxyz/python_sutff | /ex25_find_maximum_tb.py | 1,029 | 4.375 | 4 | '''
ex25_find_maximum.py
Tom Bain
27/10/20
J27C76 Software Design and Development
Standard Algorithms - Find Maximum
'''
def get_max_value(data):
'''
Returns the largest element/value within the data array/list.
Assumes at least one entry in the data.
Assumes no duplicates.
Assumes no sorting
... |
c8b448e3af70822f57a6d0826cff6f18e56a19b3 | kongjingchun/PyTest | /test01/test01_05_03/package_enmerate.py | 228 | 3.515625 | 4 | # coding:utf-8
# @Create time: 2021/3/22 8:14 下午
# @Author: KongJingchun
# @remark: 枚举函数
# 枚举打印列表
names = ['孔敬淳', '王野', '卢晓倩']
for index, item in enumerate(names):
print(index, item)
|
1bb577fef924beda2d45dc2fe8ba2f3f617f8ecc | beardbytes/python | /methods.py | 981 | 3.78125 | 4 | import datetime
class Employee:
def __init__(self, first, last, pay) -> None:
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
@classmethod
... |
69519c585882c2314a62df89ece85b5eef866849 | JayVeezy1/adventofcode | /Day_11.py | 1,836 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 20:09:39 2020
@author: Jakob
"""
import itertools
def count_seated(seats):
return list(itertools.chain(*seats)).count('#')
def count_adjacent_seats(row_id, col_id, seats):
counter = 0
adjacent = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (... |
5af8df5a47f434b4a26e3748b47d65edb675b338 | dengl11/Leetcode | /problems/split_linked_list_in_parts/solution.py | 826 | 3.5 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
l = 0
curr = root
while curr:
l += 1
curr = cur... |
7d9695e9e4cc482b2694ef1ceb20f0f9a9f8661b | albertogarcia13/PY-Exercices | /Exercise6.py | 330 | 3.859375 | 4 | lista1 = [1,2,3,4]
lista2 = [5,6,7,8]
lista1 += lista2
print(lista1)
tupla1 = (1,2,3,4)
tupla2 = (5,6,7,8)
tuplaf = tupla1 + tupla2
print(tuplaf)
diccionario1 = {"item1": 1, "item2": 2, "item3": 3, "item4": 4}
diccionario2 = {"item5": 5, "item6": 6, "item7": 7, "item8": 8}
diccionario1.update(diccionario2)
print(dicc... |
e77f629d64cbd0f930e06cd64b1b51998cb86bb8 | josephmachado1991/edd | /EDD.py | 6,964 | 3.515625 | 4 | #!/usr/bin/python
import sys
import os
import csv
import operator
def create_var_dict( data_type_file ):
# initialize variable dictionary and open data type file
var_dict = {}
f = open(data_type_file, 'r' )
csvf = csv.reader(f)
# loop over each line and load variable, data_type into var_dict
... |
baa1b359e797c3382d05f8b3f91dc114890a8ca7 | KevinAS28/Python-Neutron-Brain-Server-Web-Server-Project | /changeanyindir.py | 1,030 | 3.75 | 4 | #!/usr/bin/python3
import os
import re
import sys
print("Change anything in dir, file name, dir name, inside text")
startdir = input("start directory: ")
if (startdir=="" or (os.access(startdir, os.W_OK)==False)):
startdir = os.getcwd()
print("Startdir: %s"%(startdir))
dari = input("What you want to replace (Using... |
75a2eec052641721a7d7ac621282627d07100e3a | ezequiasOR/Exercicios-LP1 | /unidade3/selecao.py | 522 | 3.53125 | 4 | # coding: utf-8
#UFCG - Programação I - 2018.1
#Aluno: Ezequias Rocha
#Questão: Seleção Projeto - Unidade 3
cre = float(raw_input())
meses = int(raw_input())
entrevista = int(raw_input())
if cre < 7 and meses < 6:
print 'Candidato eliminado. CRE e experiência abaixo do limite.'
elif cre < 7:
print 'Candidato elimi... |
cfdcd3b00702bdc5e3845c528924c6caa8ef3d60 | Aasthaengg/IBMdataset | /Python_codes/p03252/s643598565.py | 376 | 3.5625 | 4 | from collections import Counter
s = input()
t = input()
#文字の順番入れ替えは可能
#文字の個数は増やせない
#結局はaabbbなら2,3になる
#abcdbならa:1,b:2,c:1,d:1
s_dict = Counter(s)
t_dict = Counter(t)
s_val = list(s_dict.values())
t_val = list(t_dict.values())
s_val.sort()
t_val.sort()
if s_val == t_val:
print('Yes')
else:
print('No')
|
667ea109da8fd9f5a9eee543cbffb8e7fb4a0e6d | naeimsalib/Sorting_Algorithms_Python | /SelectionSort.py | 536 | 4.125 | 4 | #Time O(N^2) time | O(1) Space
def SelectionSort(array):
current = 0
while current < len(array) - 1:
smallest = current
for i in range (current + 1, len(array)):
if array[smallest] > array[i]:
smallest = i
swap(current, smallest, array)
current += 1
... |
4ae9cd754bc4614960af729ce3ddd5e779b87f89 | divyamodi128/Python-Practice | /Sorting_Algo/FindRepeatingchar.py | 768 | 3.734375 | 4 | def findrepeats(str):
for i in range(len(str)):
count = 0
for j in range(i,len(str)):
print(str[i], str[j])
if str[i] == str[j]:
count += 1
if count >= 3:
print(str[i] * count)
str = str.replace(str[i] * count, '')
print('Fi... |
8f0900c3c3500728fd8d112f7c470fd97974f808 | FreddyManston/Misc | /PythonPrograms/PyGame/PyGameTutorial/PGBasics.py | 3,689 | 3.65625 | 4 | import pygame
import time
def start_up():
""" Set up the game and run the main game loop """
pygame.init() # prepare the pygame module for use
main_surface = pygame.display.set_mode((480, 480)) # Create surface of (width, height).
my_text = pygame.font.SysFont("Comic Sans", 17).render("Click this block for Batma... |
abaa30791f89651441ff1c2282d7ab0b3874de47 | DanSohn/AmazonPriceTracker | /AmazonPriceTracker.py | 4,586 | 3.703125 | 4 | """
A quick project where I can get a url from an amazon page, and then given credentials and a price range,
it will email the user when the item falls under the price range
Things to do:
Get information from amazon page
Get user's information
Send email
Do I want it running every hour? Do I need to write a script to h... |
7eaaebddb16fb1f2d66e29357787b317e52490cb | ehabosaleh/parallelism | /multiprocessing/Example_2/data_parallelism.py | 533 | 3.515625 | 4 | import time
from multiprocessing import Pool
import numpy as np
def square(x):
return x**2
if __name__=='__main__':
numbers =np.linspace(1,10000000)
p=Pool(4)
t1=time.process_time()
print(p.map(square,numbers))
t2=time.process_time()
p.close()
p.join()
print("executing time when using po... |
9d6273ad21bf217c83a3576ca32f8f93f7aadb47 | ko-takahashi/college | /CS596/Homework/HW3/main_part1.py | 6,144 | 3.71875 | 4 | import math
import numpy as np
import matplotlib.pyplot as plt
from getDataset import getDataSet
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
# Starting codes
# Fill in the codes between "%PLACEHOLDER#start" and "PLACEHOLDER#end"
# step 1: generate ... |
350653a916481644381841c1c9492e6c5c76774c | jsliacan/misc | /project-euler/p66.py | 451 | 3.75 | 4 | #!/usr/bin/env python
# Problem 66
# won't work -- too slow!
from __future__ import division
from math import sqrt
"""
since (x-1)(x+1) = x^2-1
we have
"""
Dmax = 1000
Xmax = 0
dmax = 0
for d in range(2,Dmax+1):
if sqrt(d).is_integer():
continue
print d
y = 1
x = sqrt(d*(y**2)+1)
while ... |
eefe89bd4b1b648369f0a34143bc0397ad686811 | khadak-bogati/Introduction-to-Computer-Science-and-Programming-Using-Python | /Prblomeset2.py | 3,236 | 3.96875 | 4 | Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest ra... |
954dcdc5bb059efe07324bf84c844482b134aa56 | joashdev/python-challenge | /inversion.py | 3,323 | 3.9375 | 4 | """
Counting Inversion
#Counting Inversion traverses through a given list then counts the inversion in the list
# a pair(x,y) is considered inversion when index(x) < index(y) but value(x) > value(y)
#This algorithm uses Divide and Conquer recursive-approach,
# specifically a modified Merge-And-Conquer algorit... |
33aa13b512f46d66b6bba511cd975ef7aa0a91cb | savirnosaj/codingDojo | /python_stack/Python/python_fundamentals/insertionSort.py | 591 | 4.125 | 4 | # Insertion Sort
# Execute insertion sort
def insertionSort(arr):
for count in range(1, len(arr)):
temp = count #temp will reset through each iteration
while temp > 0 and arr[temp - 1] > arr[temp]: # will have indexerror if try to go beyond 0 and checking if index before is greater
arr... |
37749cf214ef705f87393d877fc454c1ee92019f | sourcery-ai-bot/Python-Curso-em-Video | /python_exercicios/desafio064.py | 660 | 3.96875 | 4 | #Crie um programa que leia vários números inteiros pelo teclado.
# O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
# No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).
n = c = s = 0
n = int(input('Digite um número [999 para ... |
e90e39a6e609cc2a887dcb73f04f9406eb623ea5 | Salishoma/My-Code-House | /src/com/python/zeroFilledSubArrays.py | 863 | 3.875 | 4 | '''
2348. Number of Zero-Filled Subarrays
Given an integer array nums, return the number of subarrays filled with 0.
A subarray is a contiguous non-empty sequence of elements within an array.
Input: nums = [1,3,0,0,2,0,0,4]
Output: 6
Explanation:
There are 4 occurrences of [0] as a subarray.
There are 2 occurrences... |
8324fa28f571944426acc35ad5f1ee6b0cbd945d | Krispy2009/work_play | /sb2.py | 3,672 | 3.515625 | 4 |
from string import ascii_lowercase
import sys
global finished
global queue
global my_words
queue = []
class Node:
def __init__(self, word, parent=None):
self.word = word
self.children = []
self.parent = parent
def get_children(self):
global my_words
#change the word ... |
12b67cb4b2c670cf7bdb7d4c4803914a7d0760cb | mikedim/RSA-ElGamal-Demo | /rsaBob.py | 424 | 3.90625 | 4 | ######Bob RSA######
import support
print("------WELCOME BOB: RSA Encryption------")
print("Enter N value received from Alice")
n=input()
print("Enter e value received from Alice")
e=input()
print("Enter integer to encrypt: ")
xin=input()
if xin>=n:
print("Invalid input, message x must be an integer less than n")
els... |
539506b63b232b4822fd4a2c96b89372cda29492 | porrametict/learningSpace | /PythonWithChulalondkorn/for_loop2.py | 454 | 3.71875 | 4 | # def temperature_table():
# for celsius in range(101):
# F = (celsius*9/5)+32
# print(celsius,"=",F)
# temperature_table()
# def mult_table(from_n,to_n):
# for i in (from_n,to_n):
# for j in range(1,13):
# print("{} x {} = {}".format(i,j,i*j))
# print("---"*40)
# mu... |
0a380297dfd81c638e2ab55e2ed77e9cf09cb7cc | Adastraea/WC-Generator | /wcgenerator.py | 3,704 | 3.5625 | 4 | import random
from wcnaming import *
from wcprofile import *
def generateNameList():
while True:
numnames = input("How many names to generate? ")
try:
numnames = int(numnames)
except:
print("Invalid input. Please enter a number.")
continue
break
... |
4ed10f97d0f33374d98977f2ccd00db7a589bdc5 | Sashkow/GeneticAlgorithms | /population.py | 3,831 | 3.96875 | 4 | from collections import UserList
from dna import ListDna
from gene import BoolGene
import random
import copy
class Population(UserList):
"""
Population of DNA sequences in a genetic algorithm
arguments:
DnaClass -- class for DNA, e.g. ListDna or DictDna
GeneClass -- class for gene, e.g Boo... |
716e999386a2fef99980fd1dab113e1f51147389 | imtj1/NeuralTuringMachine_EulerianPath | /eulerian_path_task/graph_utils.py | 7,934 | 3.90625 | 4 | from operator import itemgetter
import networkx as nx
from collections import deque
def is_semieulerian(G):
"""Returns ``True`` if and only if ``G`` has an Eulerian path.
An Eulerian path is a path that crosses every edge in G
exactly once.
Parameters
----------
G: NetworkX ... |
47705e8915bb006112ff8425e42bf92db6dead1e | kazshidara/leetcode-practice | /dictionaries.py | 599 | 3.8125 | 4 | # 1. K most Frequent values
# :type nums: List[int]
# :type k: int
# :rtype: List[int]
def topKFrequent(nums, k):
dict = {}
for i in nums:
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
arr = sorted(dict.items(), key = lambd... |
00afd4229f76984e465f3d6a904f073eab8ceed7 | aralyekta/METU | /CENG111/w6/hangman.py | 404 | 3.65625 | 4 | def hangman(str1,str2,num):
len1 = len(str1)
len2 = len(str2)
if len1 > len2:
return "lose"
elif str1 == str2:
return "win"
elif len1 == len2 and str1 != str2:
return "lose"
a = 0
for i in range(len2):
if str1[i] == str2[i]:
continue
else:
... |
0239c45475af0ab0a58015a421a76c4141bc7d9a | preetam-patel/task1 | /pald.py | 133 | 4.0625 | 4 | def ispalindrome(s):
return s== s[::-1]
s= input('enter the word:')
res = ispalindrome(s)
if res :
print('yes')
else:
print('no')
|
a4576e69789645357f44345f7bed8dec2b9fb0aa | daniel-reich/ubiquitous-fiesta | /Z2mhqFLe9g9ouZY64_4.py | 267 | 3.59375 | 4 |
def is_valid_subsequence(lst, sequence):
lst = list(filter(lambda x: x in sequence,lst))
if any(x not in lst for x in sequence):
return False
if lst == sequence:
return True
return is_valid_subsequence(lst[lst.index(sequence[0])+1::],sequence[1::])
|
a564ba2cac49aea70d84031344f2753fa1248a9a | 111110100/my-leetcode-codewars-hackerrank-submissions | /leetcode/arraySign.py | 2,351 | 3.890625 | 4 | from typing import List
class Solution:
def arraySign(self, nums: List[int]) -> int:
p = 1
t = [p:=p*v for v in nums]
return 1 if p > 0 else -1 if p < 0 else 0
answer = Solution()
print(answer.arraySign([-1,-2,-3,-4,3,2,1]))
print(answer.arraySign([1,5,0,2,-3]))
print(answer.arraySign([-... |
ccd16068f58b3e38da7afd53625234fd203b1354 | Ephrao1/Password-locker | /user.py | 1,246 | 4.0625 | 4 | class User:
"""
Class that generates users new instances .
"""
user_list = []
def __init__(self,acc_name,user_name,password,email):
self.acc_name = acc_name
self.user_name = user_name
self.password = password
self.email = email
def save_user(self):
'''
... |
b84fc13c4282c49108438cd00160b05c7d37594d | tomytjandra/college-coursework | /NLP/basic nltk.py | 4,881 | 3.578125 | 4 | def clear():
for i in range(5):
print()
text = "On April 8, 2018, Persekutuan Oikumene (PO) BINUS held an Easter Service to commemorate the resurrection of Jesus Christ. BNEC sent some of its delegations to attend the invitation. It was a great event with all the activities and the warm atmosphere containe... |
1fa8c6fcd09f715d4fd6efd4ca89a18a8d02cb13 | fvcandal/project | /PMLFVC.py | 4,926 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Pratical Machine Learning
# ## Fátima Vilela Candal
# # Data processing
# The original training and test data has 160 variables. The columns with NA entries have been removed. Five (5) variables were removed.
# In[498]:
# Importing Libraries
import matplotlib.pyplot as pl... |
929f8b961f38e6750dff7f71f9bcf2733b69afc8 | virtual/fcc-python-projects | /time-calculator/time_calculator.py | 2,157 | 4.0625 | 4 | import math
# Return the day name of an equivalent day index #
def getDayNameByNum(dayIndex):
if (dayIndex == 0):
return 'Monday'
elif (dayIndex == 1):
return 'Tuesday'
elif (dayIndex == 2):
return 'Wednesday'
elif (dayIndex == 3):
return 'Thursday'
elif (dayIndex == 4):
return 'Friday'
... |
56003ac62a71b38f7f6903261c603b415d5b125c | Shohet-Val/Python | /downloader_pages.py | 1,266 | 3.765625 | 4 |
#прочитать сайт и посчитать статистику использования слов с# или python
from urllib.request import urlopen
html = urlopen("https://ru.wikipedia.org/wiki/Python").read().decode('utf-8')
s = str(html)
print('Сравнительная частота в статьи из Википедии о Питоне')
print('Частота С++ ', s.count('C++'))
print('Частота Pyth... |
93a740d639aac76a7d7f4db91b81d53017df4265 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/151_10.py | 1,414 | 4.84375 | 5 | Python | How to copy a nested list
In the previous article, we have seen how to clone or Copy a list, now let’s
see how to copy a nested list in Python.
**Method #1: Using Iteration**
__
__
__
__
__
__
__
# Python program to copy a nested list
# List initialization
... |
6dcd89c3a16a0200d15907b9ad60b2e1f64d1022 | m-wieloch/blackJack | /GUI_start_game.py | 1,097 | 3.5 | 4 | from tkinter import *
import sqlite3
# def buttom_click():
def myClick():
playLabel = Label(root, text="CDN :)")
playLabel.grid(row=4, column=2)
# def show():
# myLabel = Label(root, text=var.get()).pack()
root = Tk()
root.geometry("500x200")
root.title("BlackJack")
root.config(bg="sea green")
blackjack... |
bf2d7a46fd82fa2282fced9b639cb2e7532c50ff | szlevinli/AuraAIHomework | /sources/least_squares_method.py | 1,765 | 3.84375 | 4 | import numpy as np
from matplotlib import pyplot as plt
def least_squares_method(v_x, v_y):
"""最小二乘法
该方法仅支持二元一次方程 y = mx + c
Arguments:
v_x {ndarray 1D} -- 样本数据中的特征值
v_y {ndarray 1d} -- 样本数据中的真实值
Returns:
float -- 斜率 m
float -- 截距 c
"""
# compute mean
mean... |
68e6aedab3c0f64305f555b77dfd9a9bee7d4db1 | shacharSirotkin/SBR_2018 | /SBR/SymbolicPlanRecognition/PathNode.py | 2,349 | 3.65625 | 4 | from Node import Node
class PathNode(Node):
def __init__(self, tree_node):
self._parent = None
self._child = None
Node.__init__(self, tree_node.get_ID(), tree_node.get_label(), tree_node.get_is_root(),
tags=tree_node.get_tags(), seq_of=tree_node.get_prev_seqs(),
... |
fecae0bb124b379ff53e1e5853d3461065286289 | JeongJaeWook/pystock_jw | /gui/basic2_label.py | 519 | 3.5625 | 4 | from tkinter import *
rt = Tk()
rt.title("재욱이꺼")
rt.geometry("640x480")
label1 = Label(rt, text="Hi")
label1.pack()
photo = PhotoImage(file="check.png")
label2 = Label(rt, image=photo)
label2.pack()
def change():
label1.config(text="또만나요") #text를 바꿀때 config 쓴다
global photo2 #가비지컬렉션 되지 않도록 global 변수 설정
... |
7c8682c2e287f12962e013e33f70f187a7b9312f | tanzidakazi/Boring-Stuff-With-Python | /ListAndString.py | 2,013 | 4.3125 | 4 | # index() List Method
# append() List Method
# insert() List Method
# remove() List Method
# sort() List Method
'''import copy
friendList=['Mahmuda', 'Mazdia', 'Samiha', 'Sherin', 'Shegufta', 'abc', 'qwe']
print('Index of Mahmuda is ')
print(friendList.index('Mahmuda'))
for i in range(len(friendList)):
print('Ind... |
6018c3f22e34f7a64f970658928f17a58bc75a2f | arnav900/Dcoder-Challenges | /Easy/Python/The_light_Switch.py | 156 | 3.703125 | 4 | s1, s2 = [int(i) for i in input().split()]
if s1 and s2:
print(0)
elif not s1 and s2:
print(1)
elif s1 and not s2:
print(1)
else:
print(0)
|
19c4d63a769367eec7f7efebb821d61bd89f3e2f | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/dlymuh001/question3.py | 539 | 3.828125 | 4 | print("Independent Electoral Commission")
print("--------------------------------")
print("Enter the names of parties (terminated by DONE):")
print()
election_results = {}
party = ""
while party != "DONE":
party = input()
if party == "DONE": break
if (party in election_results) == False:
e... |
a299f78b4efd23124414bcd342f4df7621eaefbf | yongmon01/AlgorithmStudy | /자료구조/sort/selectionSort.py | 615 | 3.9375 | 4 | # 불안정 정렬 / 시간 O(n**2) / 공간 O(n)
def selection_sort(my_list):
for i in range(len(my_list)):
min_index = i
for j in range(i, len(my_list)):
if my_list[j] < my_list[min_index]:
min_index = j
my_list[min_index], my_list[i] = my_list[i], my_list[min_index]
# 테스트 1
li... |
75d1985fbad762304991c22d56fef6a01cb4eb39 | sshalu12/turtle-programs | /turtle_random_walk.py | 468 | 3.703125 | 4 | from turtle import Turtle, Screen
import random
import turtle
turtle.colormode(255)
directions = [0, 90, 180, 270, 360]
t1 = Turtle()
t1.pensize(15)
t1.speed("normal")
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
rr = (r, g, b)
return rr
... |
a5b11c2deb13a9444096030d422418fa5cf26306 | EricVenom/myfirstcalculator | /calculator.py | 1,456 | 4.1875 | 4 | calculator = "On"
def sum():
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
result = x + y
print(f"The sum of {x} and {y} is: {result}")
print()
def sub():
x = int(input("What is the first number? "))
y = int(input("What is the second ... |
644a1281eb6216eb9e0991c9e6839afbf45b4831 | hguochen/code | /python/questions/ctci/arrays_and_strings/is_unique.py | 1,003 | 4.09375 | 4 | """
CtCi
1.1 Implement an algorithm to determine if a string has all the unique characters.
What if you cannot use additional data structures?
"""
def is_unique_using_hashtable(word):
"""
Time: O(n)
Space: O(n)
where n is the word length
"""
if not word:
return False
table = {}
... |
ece6c049b034ec2cd68b66686fecb9e9a822b229 | bartnic2/Python-Guides | /2 - Program Flow Control in Python.py | 6,830 | 4.28125 | 4 | # Indenting: Note that one indent (or tab) is equivalent to 4 spaces. Try not to mix up spaces and tabs!
# Note the for look is calling the print method, which makes up the code block; everything with the same level
# of indentation is part of the same code block
# Also, you can select "reformat code" from the c... |
d9cf72221e90b16bda1be3f3f6017d9202653e42 | worldofmagic/leetcode | /python/73.set-matrix-zeroes.py | 708 | 3.546875 | 4 | #
# @lc app=leetcode id=73 lang=python3
#
# [73] Set Matrix Zeroes
#
# @lc code=start
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
rows = len(matrix)
cols = len(matrix[0])
zero_e... |
938df9342a56c9d629f7dbf7e9222678c737a073 | Vigyrious/python_fundamentals | /Dictionaries-More-Exercises/Ranking.py | 1,339 | 3.515625 | 4 | dect_contests = {}
dect_submissions = {}
command = input()
while command != "end of contests":
contest, password = command.split(":")
dect_contests[contest] = 0
dect_contests[contest] = password
command = input()
command = input()
while command != "end of submissions":
contest, password, username... |
47775db30df01709c789c1e4b78b10a92b74d91b | Ashishchougule009/Practice-examples | /Practice/Basics1/e11.py | 166 | 3.8125 | 4 | def myfun(list,n):
if n in list:
return True
else:
return False
list = [1,5,3,8]
print(myfun(list,3))
print(myfun(list,-1)) |
95fef61c70a3445d4e6c626a736664733c10ae11 | Mengeroshi/Python-Crash-Course-exercises | /chapter_5/5.9_no_users.py | 318 | 4 | 4 | usernames = ["admin", "mengeroshi", "gartox", "satoshi", "mendax"]
if usernames:
for user in usernames:
if user == "admin":
print("Hello admin, would you like to see a status report?")
else:
print(f"Hello {user}, great to see you again")
else:
print("There's no users") |
d1183c310c5a30c911a6ad3156a7539bda1b4db1 | Herophillix/cp1404practicals | /prac_06/people.py | 1,985 | 4.09375 | 4 | """
Describe many people in a table
"""
import math
from person import Person
from table import *
def get_input(prompt):
"""Get user input as raw value"""
user_input = input(prompt)
while user_input == "":
print("Input cannot be empty")
user_input = input(prompt)
return user_input
de... |
660795974fb4106aa2333b5c6cd819e48899e8d7 | renansald/Python | /cursos_em_video/Desafio69.py | 755 | 3.875 | 4 | countIdade = nHomens = nMulheres = 0;
while(True):
idade = int(input("Informe a idade: "));
while(True):
sexo = str(input("Informe o sexo da pessoa[M/F]")).strip().upper();
if((sexo == 'M') or (sexo =='F')):
break;
if(idade > 18):
countIdade += 1;
if(sexo == 'M'):
... |
ec626fcce05227e389111ecdb0c34538cbe6e418 | ssh6189/2019.12.16 | /배열insert.py | 396 | 3.859375 | 4 | import numpy as np
a = np.arange(1, 10).reshape(3,3)
print(a)
#a 배열을 일차원 ㅐ열로 변환하고 1번 index에 99추가
np.insert(a, 1, 999)
#a배열의 axis 0방향 1번 인덱스에 추가
#인덱스가 1인 row에 999가 추가됨
np.insert(a, 1, 999, axis=0)
#a배열의 axis 1방향 1번 인덱스에 추가
#index가 1인 column에 999가 추가됨
np.insert(a, 1, 999, axis=1)
|
062b51d8709deb5bddf86a443062b63a86d23748 | shockim3710/Baekjoon-Algorithm | /bronze/14652_나는 행복합니다~.py | 134 | 3.515625 | 4 | num = input()
N = int(num.split(" ")[0])
M = int(num.split(" ")[1])
K = int(num.split(" ")[2])
x = int(K/M)
y = int(K%M)
print(x, y) |
3e4002b358878f61598ad5a686abc96b944b89bb | zeeshan1414/AlgoExpert-Solutions | /0023. bst-construction.py | 3,109 | 3.65625 | 4 | class BST:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
# O(log(n)) time | O(1) space
def insert(self, val):
currNode = self
while True:
if val < currNode.val:
if currNode.left is None:
cu... |
c3967c681e0c77158330fe12f14fde2f94143102 | albamdr/TFG | /CÓDIGO/PROBLEMA DE LA MOCHILA/read_knapsack_files.py | 848 | 4 | 4 | def read_knapsack(filename):
"""
Lee el fichero filename y devuleve el número de items, el peso máximo de la mochila y los items
input:
filename:: Str, nombre del fichero en el que se encuentra la instancia
output:
N:: Int, número de items
max_weight:: Int, peso má... |
47324c36dbfbe50d9841db69409191b872639f8f | kamireddym28/Technical_Interview | /solutions.py | 5,811 | 3.765625 | 4 | ## Question 1:
def anagram(s1, t1):
s1 = list(s1)
t1 = list(t1)
s1.sort()
t1.sort()
return s1 == t1
def question1(s, t):
complete_string = len(s)
matching_substring = len(t)
for i in range(complete_string - matching_substring + 1):
if anagram(s[i: i+matching_substrin... |
9d2f5c6ecfc4f36c815349d090a2910891c1eb24 | captainjack331089/captainjack33.LeetCode | /LeetCode_Hash_Table/409_Longest_Palindrome.py | 842 | 3.90625 | 4 | """
409. Longest Palindrome
Category: Hash Table
Difficulty: Easy
"""
"""
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the len... |
d28e56c882bcc6cd28263638c48831357ece5d6e | VB6Hobbyst7/Pre-release-Materials | /June-2021/OL/Variant 21/Python/main.py | 6,579 | 4 | 4 | # DECLARATIONS
candidateNames = ["", "", "", ""]
candidateVotes = [0, 0, 0, 0]
groupStudents = 0
voteAbstentions = 0
numCandidates = 0
def task1():
# DECLARATIONS
global groupStudents
global numCandidates
groupName = input("Enter the tutor group name: ")
if groupStudents < 2 or groupStudents > ... |
a2cf1f28698ce6eb9de2976f0b962bae61db3016 | AlphaGoat/DnDHelper- | /spell_json_parser.py | 1,722 | 3.78125 | 4 | import json
def open_spells_json(path="/home/peter/Programming/Python_Files/" +
"DnDHelper/SpellConfigFiles/5e-spells-master/spells.json"):
with open(path) as spells_data_json:
spells_data = json.load(spells_data_json)
# Make the name of spells invariant by spacing and capitalization
... |
7f45d302d4779d0f3c0900713f3b6ecf5c54c55b | amalphonse/Python_WorkBook | /29.py | 230 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 19:48:40 2017
@author: Anju
"""
from math import pi
r =10
def liquid_volume(h):
l_v = ((4 * pi * (r**3))/3)-((pi * h**2 *(3*r - h))/3)
return l_v
print(liquid_volume(2)) |
f9ec68cdecdc9b54a90d38e803e3660c6dd24360 | prarthananbhat/Algorithms | /prime_numbers.py | 310 | 3.8125 | 4 | n= 16
p=2
isPrime = [True for i in range(n+1)]
print(isPrime)
while p*p < n:
if isPrime[p] == True:
for i in range(p*p,n+1,p):
isPrime[i] = False
p+=1
prime_list = []
for p in range(2,n+1):
if isPrime[p]:
prime_list.append(p)
print(prime_list)
#SieveOfEratosthenes |
4e8e0de8ea3ddd90c905b295802ea6083db35c3a | issacianmutiara/Issacian-Mutiara-Paska_I0320053_Tiffany-Bella_Tugas-3 | /I0320053_Exercise 3.7.py | 320 | 3.84375 | 4 | #Contoh cara menghapus pada Dictionary Python
dict = {'Nama': 'Issacian', 'Umur': 19, 'Kelas': 'First'}
del dict['Nama'] # Hapus entri dengan key 'Nama'
dict.clear() # Hapus semua entri di dict
del dict # Hapus dictionary yang sudah ada
print("dict['Umur']: ",dict['Umur'])
print("dict['Sekolah']: ",dict['Sekolah'])
|
3863f5d6183105318092e3de33ce718bdf646628 | SiddhiShirke/-IT-TOOLS | /class rectangle.py | 1,244 | 4.25 | 4 | class Rectangle:
def calculate_area(self):
#this function will accept input of length and breadth and calculate area
self.width = int(input("Enter Length:"))
self.height = int(input("Enter breadth:"))
area = self.width*self.height
print(area)
return (area)
def... |
728b043c4142771c49f7a98b1ecb673378cd618b | AdamZhouSE/pythonHomework | /Code/CodeRecords/2734/58547/307562.py | 776 | 3.65625 | 4 | def my_hash(string):
total = 0
total += len(string) * ord(string[0]) * 1428571
i = 0
mul = 37
while i < len(string):
total += mul * ord(string[i])
i += 1
mul += 7
return total
def func():
arr = [int(x) for x in input().split()]
string = input()
for i in rang... |
396801cc292788d3570ebf1f3d9580a5b20c46ea | RobertMcCutchen/DigitalCrafts_Assignments | /July/July 4th/alphabetize_string.py | 374 | 3.875 | 4 | import collections
string = input("Enter a string: ")
chars = "`*_{}[]()>#+-.!$?"
for c in chars:
string = string.replace(c, " ")
array = sorted(string.lower().split())
print('\n')
print(array)
counter = collections.Counter(array)
most_common_word = counter.most_common(1)
print('\n')
print(f'The most common ... |
521d17be99dadaba57e6ea2c999b4036252ccbe7 | gogozd/SIT1718 | /Osnove programiranja/Vjezba 8/vjezba8_zd01.py | 684 | 3.6875 | 4 | # Gordan Volarević
# Vježba 8, zadatak 1
import math
def zbroj(a=0, b=0):
'''Funkcija zbroj vraća zbroj brojeva a i b'''
return a + b
def zbroj_znamenaka(n):
if n < 0: n *= -1
zbroj_n = 0
while n != 0:
zbroj_n += n % 10
n //= 10
return zbroj_n
def udaljenost_... |
019c77d79012f553191dba2e31a72614eec4aaa8 | pepi99/MMAssignment | /Grid.py | 3,656 | 3.703125 | 4 | __author__ = "Petar Ulev"
import numpy as np
# Green vs red
# Green - 1
# Red - 0
class Grid:
def __init__(self, grid):
# Generation Zero
self.grid = grid
self.x = self.grid.shape[1] # number of columns
self.y = self.grid.shape[0] # number of rows
assert self.is_valid_gr... |
1e859b5181fd51bf32f72f972a4db90f8fc3e0b0 | Lindisfarne-RB/guizero-examples | /michael.py | 211 | 4.0625 | 4 | def sum(n1, n2):
return (n1 + n2)
n1 = float(input("Enter first number="))
n2 = float(input("Enter second number="))
result = sum(n1, n2)
print(result)
name = input("Enter your name=")
print(result, name) |
b35d9079d911495dfd290615970df1b9108e3d19 | mhjensen/Physics321 | /doc/LectureNotes/_build/jupyter_execute/chapter3.py | 72,412 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Simple Motion problems and Reminder on Newton's Laws
#
#
# ## Basic Steps of Scientific Investigations
#
#
# An overarching aim in this course is to give you a deeper
# understanding of the scientific method. The problems we study will all
# involve cases where we can appl... |
d9e38e46024b564573bd90203fb3bde88434fe63 | NurhandeAkyuz/Guess-the-number-game | /game.py | 6,895 | 4.375 | 4 | import random
def game(): #this function is used for showing main menu and working in that part
name = '' #when program starts, name is initially an empty string
password = '' #when program starts, password is initially an empty string
while True: #to make program shows the main menu... |
37c7556579878c20275bc936b52292ae8437cfb3 | l7opy4uk/python_study | /note_20160426.py | 1,782 | 4.0625 | 4 | #Function fabric
def f(n):
def g(x):
return n * x
return g
double = f(2)
triple = f(3)
l = []
# Not closed, because depends on i value
for i in range(10):
def f(x):
return x * i
l.append(f)
#closed
for i in range(10):
def f(x, i=i):
return x * i
l.append(f)
# map f... |
17360455dc825763e4c159f929580e4af17dcbd4 | MisterFili/NoDrinking | /05list_overlap.py | 643 | 4.21875 | 4 | #listOverlap
'''
write a program that returns a list that contains only the
elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
class_attendance = ['me', 'myself', 'and', 'eye']
name = input('type a name to check: ')
if name in class_attenda... |
da6b962d0cf722506ff67d6092367c8b59a12981 | banashish/DS-Algo | /100code/count_of_number_after_self.py | 1,325 | 3.8125 | 4 | # this is a modification in count inversion problem
def countInversionUsingMergeSort(arr):
temp_arr = [0]*len(arr)
ans = [0]*len(arr)
return mergeSort(arr,temp_arr,0,len(arr)-1,ans)
def mergeSort(arr,temp_arr,left,right,answer):
inv_count = 0
li,ri,mi = 0,0,0
if left < right:
mid = (le... |
3f58da6f1f9e6b32411cc5393bb3c33c744d46ef | sridarshini123/python-programming | /codekata/beginner level/prime or not.py | 159 | 4 | 4 | count=0
num=int(raw_input())
for i in range(2,num):
if(num%i==0):
count=count+1
if(count==1):
print("it is prime")
else:
print("not prime")
|
46d5d841ea069b330972efb3a3299e8ebdb4e34d | Python-November-2018/yashey_mateen | /01-python/02-python/01-required/05-for_loop_basic_2.py | 3,920 | 4.71875 | 5 | #1. Biggie Size - Given an array, write a function that changes all positive numbers in the array to "big". Example: makeItBig([-1, 3, 5, -5]) returns that same array, changed to [-1, "big", "big", -5].
def makeItBig(arr):
newarr=[]
biggie = 'big'
for i in range(0, len(arr), +1):
if arr[i]<0:
newarr.app... |
05378523cc7e1ae7d222753fbcf2bb41f1d627c6 | mozzielol/Deducing | /networks/model.py | 18,051 | 3.71875 | 4 | from builtins import range
from builtins import object
import numpy as np
from networks.layer.layers import *
from networks.layer.layer_utils import *
from copy import deepcopy
class Model(object):
"""
A fully-connected neural network with an arbitrary number of hidden layers,
ReLU nonlinearities, and a... |
211f94c9fdbab5f383c04a4c3267dc0273d02c31 | HanhHongBui/CS50-Pset6-Sentiments | /credit.py | 1,584 | 3.59375 | 4 | import cs50
#prompt for input
print("Number: ",end="")
cardnum = cs50.get_int()
n = len(str(cardnum))
if n!=13 and n!=15 and n!=16:
print("INVALID")
else:
cardnumodd= cardnum
cardnumeven=cardnum//10
count = 0
cardnum1 = []
cardnum2 = []
cardnum_multiply=[]
#sum of odd di... |
1f3d4dca04578bb6c7deb4b0987a36e7256f83bf | seanlucrussell/computing | /Python/Project Euler/10_summation_of_primes.py | 396 | 3.890625 | 4 | # filter out non primes, loop
a = 1
primes = [2]
divis = True
primenum = 2
while a < 2000000:
#we want to check to see if a is divisible by any number in primes, if not, append to primes and increase primes counter
a += 2
print a
for x in primes:
if a % x == 0:
divis = True
break
else:
divis = Fa... |
dabff042ff00e4fafdae99b1498193ef679b3790 | shrddha-p-jain/Machine-Learning-Assignments | /kmeansClus.py | 2,274 | 3.578125 | 4 | import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cluster import KMeans
import sklearn.metrics as sm
import pandas as pd
import numpy as np
# import some data to play with
iris = datasets.load_iris()
iris.data
iris.feature_names
iris.target
iris.target_names
# Store the input... |
a3451cdec046bdf0675d722da62c9b80cf17c445 | SpheITguru/DDA-Digital-differential-analyzer- | /DDA.py | 742 | 4.03125 | 4 | print("Enter the value of x1: ")
x1 = int(input())
print("Enter the value of x2: ")
x2 = int(input())
print("Enter the value of y1: ")
y1 = int(input())
print("Enter the value of y2: ")
y2 = int(input())
def ROUND(a):
return int(a + 0.5)
dx = x2 - x1
dy = y2 - y1
m = dy/dx
if (dx > dy):
st... |
64914ff64da1a46bcb15ad131a2f93b883dea165 | Aasthaengg/IBMdataset | /Python_codes/p02847/s885882291.py | 177 | 3.640625 | 4 | #!/usr/bin/env python3
def main():
S = input()
week = ['SUN','MON','TUE','WED','THU','FRI','SAT']
print(7-week.index(S))
if __name__ == "__main__":
main()
|
881ca383d70fbcb637238cc2f2e76fcd79472141 | PabloAndo/WeeklyPythonExercises | /Exercise_10/Exercise_10.py | 3,135 | 3.75 | 4 | # -*- coding: utf-8 -*-
from collections import namedtuple
from collections import defaultdict
Person = namedtuple('Person', ['first', 'last'])
class TableFull(Exception):
pass
class GuestList():
# GuestList is a list with each element being
# a Person (numedtuple) and a table number(int)
max_at_... |
1f62dbb41acd0f6bd5008bc0b3f47f4c52fbb92a | marranzr/MarTest | /python/HeadFirst/Chapter2/nester/nester.py | 565 | 4.09375 | 4 | """ This is the "nester.py" module, and it provides one function called
print_lol() which prints lists that may or may not include nested lists."""
def print_lol(the_list):
""" This function takes a positional argument
called "the_list", which is any Python list(of, possibly,
nested lists). Each... |
5e8d2bf77f390bb16c9d3cb17d87c1eb8fb71565 | siva4646/Private-Projects | /Python_Course/PROJECTS/Hangman/Hangman/task/hangman/hangman.py | 281 | 3.875 | 4 | from random import randint
print('H A N G M A N')
words = ['python', 'java', 'kotlin', 'javascript']
secret_word = words[randint(0, 3)]
word = secret_word)
guess = input(f"Guess the word: {word}")
if guess == secret_word:
print('You survived!')
else:
print('You lost!') |
93c42bfaff042d613620eee574dee0cca934d707 | gui-csilva/python | /Python/Temporario.py | 219 | 3.5 | 4 | def inteiros(primeiro, segundo, terceiro, quarto):
a = primeiro + 5
print(a)
b = segundo - 5
print(b)
c = terceiro * 5
print(c)
d = quarto / 5
print(d)
a = 1
b = 2
c = 3
d = 4
inteiros(b, c, d, a) |
81a88957b875edb6828a79753656f3a9fcb18b42 | sanket-arote/Python | /Session's Code/Addition.py | 480 | 3.96875 | 4 | # price_of_balls is a variable.......................
price_of_balls = 10
price_of_pencils = 20.09
number_of_balls = 8
number_of_pencils = 10
total = price_of_balls * number_of_balls + price_of_pencils * number_of_pencils
# print will basically print your statement...............................
print('Welcome to ... |
2191a717765fcba02c7e6232c6ff6fa28486b50f | sgrade/pytest | /practice_python/draw_a_game_board.py | 469 | 3.6875 | 4 | # http://www.practicepython.org/solution/2015/11/01/24-draw-a-game-board-solutions.html
def print_horizontal(dimension):
print(' ---' * dimension)
def print_vertical(dimension):
print('| ' * (dimension + 1))
def main():
dimension = int(input('Please provide game size: '))
for index in range(dime... |
20077a41adb8ae60dc5b90137bda9bb492ed886f | JoshRifkin/IS211_Assignment1 | /assignment1_part2.py | 338 | 3.859375 | 4 | class Book:
def __init__(self, author, title):
self.author = author
self.title = title
def display(self):
print(self.title + ", written by " + self.author +".")
book1 = Book("Of Mice and Men", "John Steinbeck")
book2 = Book("To Kill a Mockingbird", "Harper Lee")
b... |
0efe46ca8f6dacbb65fa9999fef88fa9f389d122 | jyabka/PythonExam | /10.Class.py | 290 | 3.71875 | 4 | class Str:
def __init__(self, c_string):
self.c_string = c_string
def user_input(self):
self.c_string = input()
return self.c_string
def toUpperCase(self):
print(self.c_string.upper())
c_str = Str("")
c_str.user_input()
c_str.toUpperCase()
|
6b3ccd380252c282ab7959fbbec3f90e4bd8e2bc | nelliesnoodles/StatsClass | /normal_dist.py | 5,319 | 4.125 | 4 | # Normal Distribution AKA Gaussian probability
import math
from scipy.stats import norm
#Note: z-score is the distance from the mean and it's standard deviation? *clarify*
def normal_deviation(a, b):
"""
What is the standard deviation of the data point distribution?
I need clarification on wher... |
a666d5e6809ff780061d1e495cc6d38e67178360 | ankithmjain/algorithms | /searching_algo.py | 517 | 3.734375 | 4 | arr = [1, 2, 3, 4, 9, 10, 40 ]
x = 10
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
print("By linear search", linear_search(arr, x))
def binary_search(arr, x):
lower = 0
upper = len(arr) -1
while True:
mid = int((lower + u... |
734e7184658ebb12e3ee2bd25d866171c60914af | yaseen-ops/python-100-days-of-course | /Intermediate/day18/turtle_challenge/turtle_square.py | 404 | 3.71875 | 4 | from turtle import Turtle, Screen
def draw_square():
seemaan.forward(150)
seemaan.left(90)
color_list = ["red", "blue", "brown", "green"]
seemaan = Turtle()
seemaan.shape("turtle")
seemaan.turtlesize(1.8)
choose_color = 0
for _ in range(4):
color = color_list[choose_color]
draw_square()
seemaa... |
784b5f600f3fd46c302e5d6fc301a7771703cbd4 | combateer3/RFID-Multitool | /scanner.py | 911 | 3.640625 | 4 | import rfid
import actions
import csv
# global to store the map of uids to actions
uid_map = {}
def get_action(uid):
# getattr will return function in the actions module
return getattr(actions, uid_map[uid])
def loop():
while True:
print("Waiting for a Mifare tag...")
uid = rfid.read_c... |
9a76ff60b4ae429545006eb526d36a0dcc0c404c | memicq/ProgrammingContestAnswers | /aizu/lectures/algorithm_and_data_structure/tree/tree_walk.py | 2,829 | 3.5 | 4 | #! python3
# tree_walk.py
from enum import Enum, auto
from collections import deque
class Color(Enum):
WHITE = auto()
GRAY = auto()
BLACK = auto()
class BinaryTreeNode():
def __init__(self, parent=None, left=None, right=None):
self.parent = parent
self.left = left
self.right =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.