blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8d83df2d7700b17efdbc65edca12d48aae852b98 | MNikov/Python-Advanced-September-2020 | /Old/Python-Advanced-Preliminary-Homeworks/Comprehension/04E. Number Classification.py | 479 | 3.78125 | 4 | def classify_nums():
nums = [int(x) for x in input().split(', ')]
pos = [x for x in nums if x >= 0]
print(f'Positive: {", ".join([str(x) for x in pos])}')
neg = [x for x in nums if x < 0]
print(f"Negative: {', '.join([str(x) for x in neg])}")
even = [x for x in nums if x % 2 == 0]
print(f"... |
53958e93e12044b99dd0a8bf18fc25daee59a69c | Ivanqza/Python | /Python Advanced/PA. Tuples and Sets/Ex. 5. Phonebook.py | 460 | 3.71875 | 4 | phonebook = {}
user_number = input()
while not user_number.isdigit():
user_number = user_number.split('-')
user, number = user_number
if user not in phonebook:
phonebook[user] = number
user_number = input()
for i in range(int(user_number)):
user_calling = input()
if user_calling in... |
be4dee844f69ada1151f57d6d12079f9e97d9eb3 | codesyariah122/MyPython | /dictionaries/lat1.py | 170 | 3.890625 | 4 | orang = {'nama' : 'Linus Torvald', 'tahun lahir': 1969, 'warga negara': 'Finlandia'}
print("Nama : {}".format(orang['nama']))
print("Negara : {}".format(orang['warga negara'])) |
28f234ec211157ca88e990256f0a09ce813884c4 | shubee17/Algorithms | /Array_Searching/min_dist_occ_max.py | 456 | 3.734375 | 4 | # Minimum Distance between two occurrences of maximum
import sys
def min_dist_max_occ(Array):
max_ele = Array[0]
min_dis = len(Array)
index = 0
for i in range(1,len(Array)):
if max_ele == Array[i]:
min_dis = min(min_dis, (i - index))
index = i
elif max_ele < Array[i]:
max_ele = Array[i]
min_dis = ... |
02c5b5bf67a2d62748be36bf676f5dee5189bd05 | swastikkalyane27/prbml | /dict/multiplyAllvalues.py | 96 | 3.5625 | 4 | dict1={"a":1,"b":2,"c":3,"d":4}
mult=1
for x in dict1.keys():
mult=mult*dict1[x]
print(mult) |
a5469a8fb8bb0ac605293db9178027c6e01e2ae1 | GarvenYu/Algorithm-DataStructure | /18二叉树的镜像/treemirror.py | 1,472 | 4.125 | 4 | #!usr/bin/env python
# -*- coding: UTF-8 -*-
"""
输入一棵二叉树,输出它的镜像。
"""
class TreeNode(object):
def __init__(self, data=None, left=None, right=None):
self._data = data
self._left = left
self._right = right
def __str__(self):
if not self._left and not self._right:
re... |
c6e6d2e795b46575037b9c62be8b9823cb4159c6 | tuanhiep/expertpy | /66.staircase_traversal.py | 1,272 | 3.9375 | 4 | # Solution 1
def staircaseTraversal(height, maxSteps):
# Write your code here.
return numberOfWayToTop(height, maxSteps)
def numberOfWayToTop(height, maxSteps):
if height <= 1:
return 1
numberOfWays = 0
for step in range(1, min(height, maxSteps) + 1):
numberOfWays += numberOfWay... |
b8f587a830db02ea48ed72962b761d62b0ddf543 | rajatkashyap/Python | /latin_text.py | 2,665 | 3.796875 | 4 | '''Exercise 1 (normalize_string_test: 2 points). Complete the following function, normalize_string(s). The input s is a string (str object). The function should return a new string with (a) all characters converted to lowercase and (b) all non-alphabetic, non-whitespace characters removed.
'''
latin_text = """
Sed u... |
38c981d82a5544336b3476c6ae5cce760eee1f24 | c940606/leetcode | /Partition Equal Subset Sum.py | 1,137 | 3.640625 | 4 | class Solution(object):
def canPartition(self, nums):
"""
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
每个数组中的元素不会超过 100
数组的大小不会超过 200
---
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].
---
输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.
---
思路:
动态规划
1. 排序(从小到大)
2. ... |
5668fc78fbfb205e134190af8e0a3afad5c9f899 | Aasthaengg/IBMdataset | /Python_codes/p03605/s474660337.py | 73 | 3.703125 | 4 | N = input()
if N[0] == "9" or N[1] == "9": print("Yes")
else: print("No") |
5ba684e90af2ae9f9511d3a344dbdf7c0c20f749 | caryt/kiosk | /kiosk.py | 2,709 | 3.546875 | 4 | """Using the MySQL Employees sample database this application
allows you to login to the site and view your details.
If you are a manager of a department then you have the ability
to view your details as well as all employees of that department.
"""
from app import app
from model import Employees, Departments
from flas... |
16cb1ad216bcef2448f66b643638c28d05e5dec6 | vsdrun/lc_public | /binary_index_tree/308_Range_Sum_Query_2D.py | 1,159 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/range-sum-query-2d-mutable/description/
https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
https://brilliant.org/wiki/fenwick-tree/
https://leetcode.com/problems/range-sum-query-2d-mutable/discuss/75872/Python-94.5-Si... |
347a60e85bdc7ede60e1903a6b049ca452e6abc0 | shen-huang/selfteaching-python-camp | /exercises/1901010140/1001S02E06_stats_word.py | 3,536 | 3.65625 | 4 | text = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although pr... |
f842689e25e6e028493fd5c30cfb7899e86f4cae | kcmodev/Package_Routing_Program | /delivery_truck.py | 2,945 | 3.609375 | 4 | import datetime
from data_parser import hm
class Truck:
def __init__(self):
self.packages_loaded = [] # list of packages currently on the truck
self.hubs_visited = []
self.TRUCK_SPEED = 18 # static truck speed is 18 mph
self.current_location = ''
self.destination = ''
... |
fb0bf03ec8c81d81292ab78548a54b643d526b33 | mplaza/dataexplorations | /melaniehw1.py | 8,579 | 3.953125 | 4 | #!/usr/bin/env python
"""
Starter file for GA Data Science: HW1.
See instructions and tips (bottom of PDF) here:
https://github.com/ga-students/dat-la-07/blob/master/hw/hw1.pdf
Note: Most of these functions will only be a few lines of code!
You should only have to modify the functions to get it working --
the c... |
6e615cad918f6b9e9e474ecda76b5ecd59ca1c8d | thivatm/Hello-world | /Python/LinkedList.py | 375 | 4.0625 | 4 | # Define custom class Node
class Node:
def __init__(self, val):
self.val = val
self.next = None
# Declare nodes with values 3 and 2 in nodes A and B.
A = Node(3)
B = Node(2)
# Link node A to node B.
A.next = B
# Define variable node as A
node = A
# Print out all values of node network.
while node... |
5b3c00d113ca782e15027dd61ca9c9df75d8e900 | jgomezbo/Quiz-Maker | /codigo_fuente/webscrapping.py | 6,407 | 3.640625 | 4 | from bs4 import BeautifulSoup
from urllib.request import urlopen
import random
#Funciones para realizar el WebScraping
def scrapear():
'''
Función compuesta de distintas funciones que scrapea la página que se eligió para el proyecto y
genera varios archivos que son de interés para el programa.
... |
4edbd342b4079464866b4f2ea2bcc3627666ec14 | SHenry07/python | /python/file_and_error.py | 1,347 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time : 20:41:16/01/10/19
# Author : Hugh Sun
# File : file_and_error.py
# Software: file_and_error.py
with open('./python/pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
file_name = "/home/heng/learn/python/pi_digits.txt"
with... |
adb0c23095b5205b3ae7badb90e4266abcb4c6af | elshadaghazade/crash_course_tasks | /Group1/09-Additional-Exercises/9.3_Math_and_assigment_operators/solved.py | 1,736 | 3.78125 | 4 | # istifadəçinin doğulduğu ili soruşun və neçə yaşda olduğunu hesablayıb print edin
# ==============================================
year = input("Doğulduğunuz ili qeyd edin:")
age = 2018 - int(year)
print("Sizin yaşınız:", age)
# ==============================================
# 2022-ci ildə neçə yaşı olacaq?
# =======... |
cfacce12ed17d089bdcbe78b860ef9bbd66e0479 | forrestjan/Basic-Programming | /Week 02/oef05.py | 629 | 3.671875 | 4 | #score = float(input("Geef uw score op: "))
# if score >= 9.5:
#print("u bent geslaagt!!")
# else:
#print("Volgende keer beter :(")
# easy versie maar werkt ook met cijfers boven 20
from math import ceil, floor
score = float(input("geef je score op 20: "))
# waarde_na_de_komma WORDT 18.5 - 18 dus 0.5(want float wor... |
28d8a3fc30a115db6bceaae799b66e29f4f6ef24 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/9e27f5ca35474de797a1ad903ef39efb.py | 235 | 3.609375 | 4 | def distance(seq1, seq2):
if len(seq1) != len(seq2):
return "Sequences must have the same length."
hamming_distance = 0
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
hamming_distance += 1
return hamming_distance
|
c94f2c5f101734786d6302108d9d393a7e486a06 | futurewei/perceptron_softmax_classification | /features.py | 5,684 | 3.546875 | 4 | # features.py
# -----------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
# ... |
1af5c5a0eb481e555776888d08766bf3f346c73d | Danielral/numericalAstrophysics | /randomNumberGenerator.py | 1,503 | 3.640625 | 4 | import numpy
from matplotlib import pylab as plot
#######
###random number generator, which for each time calling it, will produce a new random number for you
lastRandom = 5761015743107 #starts with this seed, but this is actually my storage unit for later stages
print('This is my Seed: %i'%lastRandom... |
1261dbe1f8b59543b95bcfd085181d302f7d7277 | MathiasJ99/Naughts-Crosses | /naughts and crosses.py | 3,423 | 4.15625 | 4 | import random
board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]] # creates board
def viewboard():
row1 = board[0]
row2 = board[1]
row3 = board[2]
print("\n", row1, "\n", row2, "\n", row3) # outputs the board in a user friendly way
match3 = False
draw = False
used_positions ... |
bfca827790da79b055cadafdc1ee98627618b73f | athelia/hb-lab-2-1-restaurant-ratings | /ratings.py | 1,646 | 4.25 | 4 | """Restaurant rating lister."""
"""
Unzip a file
Iterate over lines
split at : ==> list of 2 items
tuple the list
dict the tuple ==> dictionary with key-value pairs
Use sorted() on the dictionary, save to a variable ==> alphabeized list of keys
Iterate over the dictionary
Unpacking and use item to index through d... |
b04e47511f6d6b0f6747da9982a1b33d9cebb926 | sadielise/cs320 | /PA2/exPQ.py~ | 1,637 | 4 | 4 | #! /usr/bin/python
import sys
# heaps here are 1 based, so read puts None in 0th element
def readNums(fnm):
f = open(fnm)
lst = [None]
for line in f:
l = line.strip().split(" ")
for s in l:
lst.append(int(s))
return lst
# heaps here are 1 based
def parent(i): return i/2
def left(i): re... |
c8477c4578a2d9e5c17e3fef61a86b3eafb71b30 | tigervanilla/Guvi | /odd_even_add.py | 76 | 3.75 | 4 | n,m=(int(i) for i in input().split())
print('odd') if n+m else print('even') |
55cd9a117840db62a9d870d7f904697b8c543376 | AbdallahMostafa/Concepts-Assignment | /Armstrong.py | 365 | 3.71875 | 4 | def armstrong (number):
sum = 0
for j in str(number):
slice = int(j) % 10
sum += slice ** len(str(number))
j = int(j) / 10
if sum == i:
return True
return False
start = int(input("Enter the start number"))
end = int(input("Enter the end number"))
for i in range(start, e... |
07fee148839fbbb93dc085451afa8f2c2543cc36 | abagaria/seq2seq | /seq2seq_vanilla.py | 1,588 | 3.625 | 4 | import sys
eng_filename = sys.argv[1]
frn_filename = sys.argv[2]
# TODO: Preprocess the dataset:
# - Shuffle the dataset
# - Split the dataset into 90-10
# - Tokenize the words into IDs
# - Pad sentences, and store sentence lengths
# - Create three outputs: Encoder input, decoder input, decoder output
# - Example en... |
98e616f5d8e432263a72f23fa41e630deb003d39 | appleface2050/Lcode | /Top Interview Questions/1.py | 477 | 3.625 | 4 | # coding=utf-8
#https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/
class Solution(object):
def removeDuplicates(self, A):
if not A:
return 0
last, i = 0, 1
while i < len(A):
if A[last] != A[i]:
last += 1
... |
c995dfa15cabb7499e8c018e4c160f1505310dcf | nervaishere/DashTeam | /python/5th_session/6def_min-max.py | 435 | 4 | 4 | listA = [18, 19, 21, 22]
print('The smallest number from listA is:',min(listA))
print('The largest number from listA is:',max(listA))
strA = 'AppDividend'
print('The smallest character from strA is:', min(strA))
print('The largest character from strA is:', max(strA))
strA = 'AppDividend'
strB = 'Facebook'
strC = 'Ama... |
cbea8954c5294f27edbad50cc153fe440bd52735 | huandoit/pyStudy | /python3-cookbook/Chapter1/1.12.py | 2,164 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/3/19 10:08
@Author : WangHuan
@Contact : hi_chengzi@126.com
@File : 1.12.py
@Software: PyCharm
@description: 找出一个序列中出现次数最多的元素
"""
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes'... |
59ca7ee6d265a418be1dc25de41bc05a277e2d5f | JATIN-RATHI/7am-nit-python-6thDec2018 | /File_Dir_mgmt/File_Operations.py | 1,592 | 4.4375 | 4 | # Python file operations :
"""
1. Open a file
2. Read or write (perform operation)
3. Close the file
# Builtin Functions:
1. open()
2. close()
f = open("test_1.txt") # open file in current directory
f = open("C:/Users/Jessicah Princess/Desktop/test_1.txt") # specifying full path
# Python File Modes:
----------... |
8dcef2f7e9babec4e78ba07e210845b7f86467a6 | Satyakaam-ui/DataScience | /Intro to Python - Medium.py | 4,176 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Here you have a collection of guided exercises for the first class on Python. <br>
# The exercises are divided by topic, following the topics reviewed during the theory session, and for each topic you have some mandatory exercises, and other optional exercises, which you are inv... |
f33d9d6739bff7bf89488039a5b0b301ba96fc17 | Jeetendranani/yaamnotes | /algorithm/11_hashtable.py | 2,182 | 3.5625 | 4 | """
11. Hash Tables
Many applications require a dynamic set that supports only the dictionary operation insert, search, and delete. For
example, a compiler that translates a programming language maintains a symbol table, in which the keys of elements are
arbitrary character strings corresponding to identifiers in the ... |
56e366105fb6ee77c098285d4e8b0d905966ba62 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/07556b74c6c24697b390ac774bd01530.py | 610 | 3.875 | 4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import string
def has_letters(msg):
# checks msg to see if standard alphabet or umlauted vowels appear.
# returns set of letters that appear which can be used as truth value.
ltrs = string.letters + 'ÄËÏÖÜäëïöü'
return(set(msg).intersecti... |
3f18dd0fdfaa80c777b6ff9b68e6c937b4ff134a | thabo-div2/python-list-and-tuples | /main.py | 184 | 3.890625 | 4 | # List Exercise 1
ages = [2, 12, 12, 14, 15, 16, 16, 17, 18, 14, 20, 20]
# Organizing the list
ages.sort()
print(max(ages))
# Removing the duplicates
print(list(dict.fromkeys(ages)))
|
4fbfd7b74bcd3fbfbb4bc89b3c8ddcd3f0a2616f | Salman-Moin/Python-CISCO-Assignments | /Assignment-1a.py | 340 | 4.15625 | 4 | #Assignment 1a
#Write a Python program to print the following string in a specific format (see the output).
#Author Salman Moin
poem = "Twinkle, twinkle, little star,\n \tHow I wonder what you are!\n \t\tUp above the world so high,\n \t\tLike a diamond in the sky.\n Twinkle, twinkle, little star,\n \tHow I wonder w... |
71fffcb8d347de1491ba55575f4310c2cc63cc0a | WotIzLove/University-labs | /PythonTutor/Тьютор 6/Задача 12.py | 134 | 3.796875 | 4 | a = int(input())
Max1 = a
Max2 = a
while a != 0:
if a> Max1:
Max2 = Max1
Max1 = a
a = int(input())
print(Max2) |
e7c3a71257ce94e4c802cf49c9f4b0dc33f4dbb3 | stephenyoder/Binary_Decimal_Converter | /bin_dec_converter.py | 3,133 | 3.71875 | 4 | ########################################################
# Programmer: Stephen Yoder
#
# Inputs: mode + binary or decimal input
# Outputs: Binary or Decimal number5
#
# Description: Binary-decimal, decimal-binary converter
########################################################
def bin2dec(bin):
bin = str(bin)
... |
cc8f2a2c1be75e55d1ab3a1be010f0c75902fb91 | keyehzy/Kattis-problems | /provincesandgold.py | 706 | 3.5625 | 4 | def provincesandgold():
hand = map(int, input().split())
buypower = [3,2,1]
hand_buypower = sum(p * q for p,q in zip(buypower, hand))
dom = [[8,6], [5,3], [2,1]]
dom_dict = {0:'Province', 1:'Duchy', 2:'Estate'}
tre = [[6,3], [3,2], [0,1]]
tre_dict = {0:'Gold', 1:'Silver', 2:'Copper'}
... |
5406a3262ca4f750c5a4e9331f95b7420bca2e78 | jharkhade/Python_Assigment_Repo1 | /assignment/assignment2/Q4.py | 164 | 4.15625 | 4 | def factorial(n):
if n < 1 or n ==1 :
return 1
else:
return (n * factorial(n-1))
n = int(input("enter number:"))
print ("Factorial:")
print (factorial(n))
|
623e4cd1e440324215417a2dcbce67d1586960a7 | ben-cook/csgo-skin-database | /SQLHelper.py | 1,384 | 3.90625 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
# create a database connection to a SQLite database
conn = None
try:
conn = sqlite3.connect(db_file)
print("Connected to sqlite database at " + db_file)
except Error as e:
print(e)
return... |
727cdb342cb19df4838059a05bc61468fecf0952 | Cozoob/Algorithms_and_data_structures | /ASD-cwiczenia/Zestaw 8 Grafy BFS i DFS/moja samodzielna implementacja BFS.py | 1,367 | 3.578125 | 4 | # Created by Marcin "Cozoob" Kozub at 03.05.2021 19:05
def BFS(G, s):
# G = (V, E), s należy do V
Q = q.Queue()
s.d = 0
s.visited = True
Q.put(s)
while not Q.empty():
u = Q.get()
for v in u.next:
if v.visited == False:
v.visited = True
... |
f90a0b7dc349d62a151fdfaf52fc85cbae8648d5 | MaxAntony/ApuntesPythonCodigoFacilito | /3.tuplas/2.comprimir_y_descomprimir.py | 1,620 | 4.5625 | 5 | tupla = (1, 2, 3, 4, 5, 6)
lista = [10, 20, 30, 40]
# la funcion zip puede recibir n cantidad de listas y tuplas
resultado = zip(tupla, lista)
print(resultado)
# lo convertimos atupla para visualizarlo
resultado = tuple(resultado)
print(resultado)
# tambien lo podemos convertir a lista
resultado = list(resultado)
pri... |
e78b6bd5cd5c07c3b7b1c0bd87e976831c160591 | martinez022jose/POO-Python | /Ejercicio3/ejercicioV3.py | 3,699 | 3.734375 | 4 | """
1. Crear una clase producto con los siguientes atributos:
- codigo
- nombre
- precio
Creale un constructor, getter y setter y una funcion llamada calcular_total, donde le pasaremos unas unidades y
nos debe calcular el precio final.
2. Añadir una clase pedido que tiene como atributos:
- lista de productos
... |
0e555dea7721583abcd495c6ccca17767effad25 | ubante/poven | /projects/magic_draft/MagicDraft.py | 10,694 | 4.15625 | 4 | import sys
from random import randint
"""
How should I signal in an 8 person draft?
There are eight players. Each player starts with a 15 card deck. The "cards" have a color from (
red, blue, green, yellow, purple) and an integer from [1:40]. The cards can repeat in a deck and
the cards are random. Each player al... |
f4747fe132764d7a5209d3245cf8359cab626993 | shreeyamaharjan/Assignment | /Data Types/QN18.py | 299 | 4.0625 | 4 | lst = []
n = int(input("Enter the size of list : "))
print("Enter the elements : ")
for i in range(n):
x = int(input())
lst.append(x)
print(lst)
greater = lst[0]
for i in range(n):
if lst[i] > greater:
greater = lst[i]
print("The smallest number from the list is : ", greater)
|
48894fce935089c62edffcb63bb4b03a0e9e4dbc | gopeek/investment-calculator | /finance_calculator.py | 2,437 | 4.28125 | 4 | import math
#user to choose type of investment i.e. investment or bond
print("Choose either 'investment' or 'bond' from the menu below to proceed \n\n investment - to calculate the amount of interest you'll earn on interest \n bond - to calculate amount you'll have to pay on a home loan \n")
#take user input
input_inv... |
da6a0d1b79d6c079ae6d523c8eb1a03981f73204 | RobGoelz/python-the-hard-way | /ex6.py | 2,298 | 4.8125 | 5 | # Sets variable x to string value and calls python format operator for integer decimal (%d) to receive value "10" into the string
x = "There are %d types of people." % 10
# sets variable binary to string "binary"
binary = "binary"
# sets variable do_not to string "don't"
do_not = "don't"
# sets variable y to string ... |
869ee5ef28a7fd1384fa73afe0b1eddbd2787bd9 | sukanyasaha007/Regression_Framework | /src/feature_selection-checkpoint.py | 1,801 | 3.5 | 4 | import sklearn
from sklearn.feature_selection import SelectKBest, f_regression, RFE
import matplotlib.pyplot as plt
def feature_ranking(X,y, estimator='lin'):
'''
gives feature rankings for all columns
parameter
-------
X: Data frame of Indepenedent columns where categorical columns are encoded
... |
09fd090002c7605155bb7e780239efcf1612fd39 | callmexss/leetcode | /solution-python3/412.fizz-buzz.223313543.ac.py | 642 | 3.515625 | 4 | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ret = []
fizz, buzz = 0, 0
for i in range(1, n + 1):
fizz += 1
buzz += 1
if fizz == 3 and buzz == 5:
ret.append("FizzBuzz")
fizz, buzz = 0, 0
... |
3b3655cfa30e7f9108bdc06d34b2573bcb452967 | rarezhang/leetcode | /string/434.NumberofSegmentsinaString.py | 570 | 4.15625 | 4 | """
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
"""
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
... |
d008a1831bb4a3fd514284e2a36ebbe8077ee0e2 | BrandonArroyo/CrackingTheCodingInterview | /Chapter1/1.1Python/isUnique.py | 426 | 3.9375 | 4 |
#Implement an algorithm to determine if a string has all unique characters?
def isUnique(s):
if len(s) > 128: # if size is smaller than all possible letters then false
return False
#possible assuming that all the characters are 128
array = [-1]* 128 # all possible places
for i in s:
if ... |
edee151e99bdba690284d615c4154c2ef8cb3e9d | kpkrishan/Investigate_TMDb_Movie_Dataset_Udacity_data_analyst_nanodegree | /Investigate a Dataset (TMDb Movie Data).py | 12,144 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# Krishan Kumar Pandey
# # Project 2:Investigate a Dataset (TMDb Movie Data)
# In this project we are going to do general data analysis of data provided to us with the help of python libraries like numpy,pandas and matplotlib.
# # Table of Contents:
# 1.Introduction
#
# 2.Dat... |
fbcfbae620ce813eb04f3941781ccfe51b9a46dd | VongRichard/Artificial-Intelligence | /Lab2/Lab2_Q8.py | 3,139 | 4.1875 | 4 | from search import *
import math
class LocationGraph(ExplicitGraph):
"""This is a concrete subclass of Graph where vertices and edges
are explicitly enumerated. Objects of this type are useful for
testing graph algorithms."""
def __init__(self, nodes, edges, starting_nodes, goal_nodes, locations):
... |
2ce09d8d77cb830efb1b29132b84c1ff6639b547 | htl1126/leetcode | /21.py | 1,058 | 4.0625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not (l1 a... |
fe8af4830f6ec97f72724f2dc3f8413d790f73e9 | nekoTheShadow/my_answers_of_yukicoder | /0843.py | 500 | 3.671875 | 4 | import math
n = int(input())
sieve = list(range(n + 1))
sieve[0] = sieve[1] = None
for x in range(2, math.ceil(math.sqrt(n)) + 1):
if sieve[x] is not None:
for y in range(x + x, n + 1, x):
sieve[y] = None
count = 0
primes = set(x for x in sieve if x is not None)
for q in primes:
... |
aeadcdea4fc3bd6ad8e01683f42b2274c2175ffe | sahthi/data | /1.py | 87 | 4.0625 | 4 | x=0
while x<3:
if x<=1:
print ("votary")
else:
print("VotaryTech")
x=x+1
|
7942836f83e24726af71bfd62c8ad4fd2560214e | C4DLabOrg/ca-training | /exercise.py | 1,043 | 4.5 | 4 | '''
>>> The Calculator assignment
1) Take three inputs from a user : a, b, c
2) a and b should be operands to perform arithmetic
operations
3) c should be the choice of operation the user would
want to perform. (+, -, %, *, **)
4) Calculate and print each output for the operations
5) get records from the user ... |
e515cb3067607be781059760e886c61c22cf94da | willbaschab/COOP_2018 | /Chapter06/U06_Ex06_TriangleArea.py | 2,671 | 4.59375 | 5 | # U06_Ex06_TriangleArea.py
#
# Author: Will Baschab
# Course: Coding for OOP
# Section: A2
# Date: 14 Jan 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: 06
# Source: Python Programming
# Chapter: 06
#
# Program Description
# This program allows the user to draw a triangle on the graphics window
... |
997948365006b9edc80958718790ebfbc2891d61 | blauks/ntnu-2 | /TDT4127 - Programmering og Nummerikk/2/Ulike typer if-setninger.py | 1,183 | 3.78125 | 4 | #!/usr/bin/python3
''' a)
tid = int(input('Hvor mange minutt har kaken stått i ovnen? '))
if tid >= 50:
print('Kaken kan tas ut av ovnen.')
print('Tips til servering: vaniljeis.')
#'''
''' b)
epler = int(input('Hvor mange epler har du? '))
barn = int(input('Hvor mange barn passer du? '))
if barn > 0 and epler ... |
190d34285241638f6c1df4176200bb3cff714262 | stiven77nj/Python | /Ejercicios.py/5-Funciones.py/Ejercicio6.py | 566 | 4.21875 | 4 | '''
Escribir una función que calcule el máximo común divisor de dos números y otra
que calcule el mínimo común múltiplo.
'''
def mcm(n,m):
if n > m:
greater = n
else:
greater = m
while (greater%n != 0) or (greater%m != 0):
greater +=1
return greater
def MCD(n,m):
rest = 0
... |
9cfbd8c47c180eb29577651b35c7501d2ba1ed09 | AdityJadhao/pythonProject | /oopsConceps/createClass.py | 631 | 3.859375 | 4 | #creation of class
class myfirstClass(): #name should be start from camelcode and : is use after class name
pass # pass is use to declare empty class , we can add body letter
ins_obj = myfirstClass() # instance of class
print(ins_obj) # this gives class mem... |
e992ef3191cb31bfec4e5e16ed5d45090d9dc669 | prajjaldhar/basic_python | /basic_python/50_constructor.py | 833 | 4.28125 | 4 | ''' __init__() constructor is a speacial method/function which is first run when an object is created
takes self and other arguments '''
class Employee:
company="Google"
def __init__(self,name,salary,unit):#constructor
print("Object is created")
#default types passed
self.salary=s... |
9b18a26963a62bf747319b06464f64d736908244 | alejandrozorita/Python-Pensamiento-computacional | /list_comprehension.py | 152 | 3.5625 | 4 | my_list = list(range(100))
print (my_list)
double = [i * 2 for i in my_list]
print (double)
pares = [i for i in my_list if i % 2 == 0]
print (pares)
|
0b45c93730f6cb8eeacecb14dddf0d6043c16d72 | jeudy/intropython0415 | /ejemplo_escritura_so.py | 486 | 4 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Programa de ejemplo que escribe una linea de números a la salida estandar
Imprimer 10 lineas con los numeros del 0 al 100, 10 números por linea
"""
numeros = range(0,101) # Genero una lista con los numeros del 0 al 100
linea = ""
for n in numeros:
linea += ",%s... |
71473a0b3cbff353e154c79c0e89e07738907e73 | samratchoudhury/HackerRank-Python | /maximize It .py | 1,448 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product
k, m = map(int, input().split())
array = []
for _ in range(k):
array.append(list(map(int, input().split()))[1:])
result = 0
for combination in product(*array):
result = max(sum([x * x for x in combination]) %... |
5ae57b4493bfc5778bf4e37fe9b5db41efde11a1 | ZachLynch123/PythonPractive | /recursion/recursion.py | 633 | 4.15625 | 4 |
def countdown(x):
if x == 0:
print("Done!")
return
else:
print(x, "...")
countdown(x - 1)
return
countdown(5)
## building factorial and power functions
def power(num, pwr):
if pwr == 0:
return 1
else:
return num * power(num, pwr - 1)
def f... |
518e634fe97ae53a3bb0d1f35b867bc3e8024988 | soumyadeep589/Tictactoe | /app.py | 1,935 | 3.515625 | 4 | import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
class Rectangle(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
class Player(object):
def __init... |
d3522fc699f98931c0c3ba5109770389ff035686 | Bahic12/Insitut | /Algorithm/LinkedList/LinkedList2.py | 358 | 3.875 | 4 | from LinkedList import Noda, LinkedList
llist = LinkedList()
llist.head = Noda('Monday')
tuesday = Noda('Tuesday')
wednesday = Noda('Wednesday')
llist.head.next = tuesday
tuesday.next = wednesday
llist.push('Sunday')
llist.insertAfter(llist.head.next.next, 'Tuesday night')
llist.append('Thursday')
llist.deleteN... |
9fa7a5852e62d7717d56c66f24d63eb00dbc1e2c | VineeshaKasam/Leetcode | /FirstLastIndicesSortedArray.py | 766 | 4 | 4 | '''
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
'''
def searchRange(nums, target):
if len(nums) == 0:
... |
2c61a8ee59cdb6637d4076de860cc20c02c12323 | liuyuzhou/ai_pre_sourcecode | /chapter3/average_1.py | 485 | 3.78125 | 4 | import numpy as np
num_np = np.array([1, 2, 3, 4])
print('初始数组:{}'.format(num_np))
print('调用 average() 函数:{}'.format(np.average(num_np)))
# 不指定权重时相当于 mean 函数
wts = np.array([4, 3, 2, 1])
print('再次调用 average() 函数:{}'.format(np.average(num_np, weights=wts)))
# 如果 returned 参数设为 true,则返回权重的和
print('权重的和:{}'.f... |
163e617a75dc74b9b362d0009172d62c951e5476 | fahmoreira/L-Python | /cursoemvideo/repo/mundo2/ex036.py | 965 | 4.0625 | 4 | # Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
# O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
# Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário
# ou então o empréstimo será negado.
from t... |
e3e3a53c4d3aef58e9f22c2385ada88ab517ebc9 | KolorowyAleksander/ean-projekt | /python/methods/__init__.py | 5,607 | 3.6875 | 4 | #!/usr/bin/env python2
"""Module for the functions themselves"""
from math import fabs
from interval import interval
from interval import imath
from interval import fpu
from interval import inf
class MyError(Exception):
"""Exception for passing message"""
def __init__(self, value):
self.value = value
... |
e9f29a0efd929f7d4d52b93f8ba8ae253301cbf6 | Irina-Nazarova/algorithms_course | /greedy_algorithms/task_backpack.py | 584 | 3.859375 | 4 | def backpack_space(cost_weight: list, weight_limit: int) -> str:
"""
:param cost_weight: [(0, 25, 50), (1, 30, 40), (2, 10, 80), (3, 2, 3)]
:param weight_limit: 36
:return: '1 2 3' displays in sorted order the numbers of items from the backpack
"""
backpack = []
cost_weight.sort(
k... |
daf6299762e39365d4e0099a36ae78a1a59bcd0a | lzxyzq/Cracking_the_Coding_Interview | /Cracking_the_Code_Interview/Leetcode/3.String/290.Word_Pattern.py | 1,528 | 3.9375 | 4 | '''
@Author: your name
@Date: 2020-06-09 17:21:16
@LastEditTime: 2020-06-10 12:19:27
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /Cracking_the_Code_Interview/Leetcode/String/290.Word_Pattern.py
'''
# Given a pattern and a string str, find if str follows the same pattern.
# Here f... |
f2b7c68e1ffbf665022ec446321c29813501a53d | janerleonardo/Python3CodigoFacilito | /Basic/busqueda.py | 481 | 4.0625 | 4 | mensaje = "Este es un texto un poco grande en cuanto a logitud de caracteres se refiere"
print(mensaje.count("texto"))
print("texto" in mensaje)
print("texto" not in mensaje)
print(mensaje.find("texto")) # Saca el indice donde esta el texto
resultado = mensaje.find("texto")
resultado = mensaje[resultado: resultad... |
90e462093bcbf5e58586f7dcb85d3b5abb8e8278 | roman807/tf-practice | /r30_imdb.py | 1,803 | 3.515625 | 4 | # for reference: https://www.coursera.org/learn/natural-language-processing-tensorflow/lecture/0N8WC/looking-into-the-details
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import nump... |
c2bd7f9dfdc262a83d193f95bce38344a2fb47cf | DanMayhem/project_euler | /143.py | 1,584 | 3.9375 | 4 | #!python
"""
Let ABC be a triangle with all interior angles being less than 120 degrees. Let X be any point inside the triangle and let XA = p, XC = q, and XB = r.
Fermat challenged Torricelli to find the position of X such that p + q + r was minimised.
Torricelli was able to prove that if equilateral triangles AOB, ... |
1fd58048ac24ddd92766cfbdf3a955497572c065 | AndreeaLoredanaIlie/algorithms | /Stacks_and_Queues/stack_min.py | 1,649 | 3.90625 | 4 | """
Implements a stack that has a function min which returns the minimum element
"""
import sys
class StackNode(object):
def __init__(self, data):
# Node element, stores data and "pointer" to next Node.
self.data = data
self.next = None
self.min = sys.maxsize
class Stack(object):
... |
a15017abb71dcbadd7ce41b47100437766f67a2e | henrykironde/Geodata | /unpack/python_code/1138OS_Code/1138OS_Code/Chapter 8/1138_08_03-flood-fill.py | 2,146 | 3.53125 | 4 | """
Crawls a terrain raster from a starting
point and "floods" everything at the same
or lower elevation by producing a mask
image of 1,0 values.
"""
import numpy as np
from linecache import getline
def floodFill(c,r,mask):
"""
Crawls a mask array containing
only 1 and 0 values from the
starting point (c=colu... |
2eccef26bb0a8c0fc7a8b945c49f6f981fda07bf | vividyellow/oldboyeduPython14qi | /第1部分-python基础(颜涛老师)/day04/day04-code/02 作业讲解.py | 2,936 | 3.765625 | 4 | # 1.请输出 name 变量对应的值中 "e" 所在索引位置?
name = "aleX leNb"
# e1 = name.find("e", 0,5 )
# print(e1)
#
# e2 = name.find("e",5 )
# print(e2)
# count = 0
# while count < len(name):
# if name[count] == 'e':
# print(count)
# count = count +1
# s1 = name[:1]
# s2 = name[1:]
# print(s1.upper()+s2)
#
# name.replace... |
13829f679ebd74324e3fd59b76ae552c8622af99 | ajitabhkalta/Python-Training | /patterns/patterns2.py | 291 | 3.65625 | 4 | import time
rows = int(input("Enter no of rows:"))
x=input("Enter char to print in pattern")
gap_row=rows
for i in range(1,rows+1):
print(x*i,end="")
for j in range(1,(2*gap_row-1)): #2*5-1=9,2*4-1.2*3-1,2*2-1
print(" ",end="")
gap_row-=1
print(x*i)
time.sleep(1) |
d7e459247d97a8b95c6bb69e1dfcc1923ca59b58 | dinfecs/mis_apuntes | /Ejercicios Python/ejercicio_terceraclase2.py | 282 | 3.546875 | 4 | for i in range(1, 11):
print(i)
for o in range(60, 71):
print(o)
for k in range(1, 1001):
print(k)
for l in range (20, 0, -1):
print(l)
num_5 = 0
for p in range (0, 51, 5):
print('5 x {numeral} = {resultado}'.format(numeral=num_5, resultado=p))
num_5 += 1 |
adc60711f7e6a743cf440da98fd7d4e2ff8c7c79 | adamacosta/euler | /pandigital.py | 764 | 3.875 | 4 | import time
def pandigital(n):
"""Input: A natural number n >= 9.
Output: The sum of all products whose multiplicand/
multiplier/product sequence is pandigital."""
products = set([])
digits = set([i for i in range(1, n + 1)])
max_num = 0
for i in range(n, 0, -1):
max_num += i * 10 *... |
62329cbaa63f937623be271018e3a0031f221337 | luizmariz/cripto | /AL13.2/AL13.2.py | 884 | 3.734375 | 4 | #atividade de laboratorio 13.2
from math import sqrt
n = input()
for x in range(n):
num = input()
num_mers = (2**num) - 1
print num_mers
r = int((sqrt(2**num))/(2*num))
print r
for x in range(1,r+1):
q = 1 + 2*x*num
print x
c = q
R = 1
A = 2
... |
12470006c9741f8b633d0df9cc5de9048ece5f22 | Damanpreet/Algorithms | /leetcode/Sorting/MergeSort.py | 799 | 3.765625 | 4 | arr = [38, 27, 43, 3, 9, 82, 10]
# arr = [4, 3, 2, 10, 12, 1, 5, 6]
def merge(l, m, r):
n1 = m - l + 1
n2 = r - m
left = arr[l:m+1]
right = arr[m+1:r+1]
i, j = 0, 0
k = l
while i<n1 and j<n2:
if left[i] > right[j]:
arr[k] = right[j]
j+=1
else:
... |
88d4fc726f114384124341052ee9a8ddca93778a | matrufsc2/matrufsc2 | /app/support/sort.py | 1,193 | 3.625 | 4 | __author__ = 'fernando'
def sort(x, y):
x = iter(x if x else []).next
y = iter(y if y else []).next
try:
xo = x()
except StopIteration:
while 1:
yield y()
raise StopIteration
try:
yo = y()
except StopIteration:
yield xo
while 1:
... |
fc86c20fd173ce3b9198151825069f25f24ec2fe | naveenprolific/python | /closestint.py | 312 | 3.53125 | 4 | def mindiff(arr):
if len(arr)<=1:return
arr.sort()
diff=arr[1]-arr[0]
for i in range(2,len(arr)):
diff=min(diff,arr[i]-arr[i-1])
for i in range(1,len(arr)):
if (arr[i]-arr[i-1])==diff:
print("(",arr[i-1],",",arr[i],")")
arr=list(map(int,input("enter the sequence here:").split()))
mindiff(arr)
|
63ef5468c20458ffcfd4f98c39e19309f3f557e4 | koirul93/Python-progate | /dasar-dasar.py | 340 | 3.703125 | 4 | # Cetak 'Hello World'
print("Hello World")
# integer
# Cetak 7 sebagai sebuah integer
print(7)
# Cetak penjumlahan dari 9 dan 3
print(9 + 3)
# Cetak '9 + 3' sebagai string
print('9 + 3')
# Perhitungan
# Cetak hasil dari 9 / 2
print(9 / 2)
# Cetak hasil dar 7 * 5
print(7 * 5)
# Cetak sisa dari 5 dibagi 2 menggun... |
60fc6e89d4f95f223ea7916e3a0d8a336ad21d2b | gharib85/moha | /data/examples/modelsystem/cubic.py | 855 | 3.765625 | 4 | from moha import *
d = 1.0 # unit cell length
def cube(d):
#define a 3D cubic lattice cell with vectors a1 a2 and a3
cell = Cell(3,[d, 0., 0.],[0., d, 0.],[0., 0., d])
#add a site labeled 'A' at positon [0.,0.,0.]
cell.add_site(LatticeSite([0.,0.,0.],'A'))
#add a bond from first site in cell... |
9ec4d4f18da6906f2d98708a72f90ddb02f040bb | randName/advent-of-code | /2019/04.py | 916 | 3.5625 | 4 | def check(number):
s = str(number)
double = sum(a == b for a, b in zip(s[:-1], s[1:]))
if double < 1:
return False
if any(int(b) < int(a) for a, b in zip(s[:-1], s[1:])):
return False
return True
def check2(number):
if not check(number):
return False
cur = None... |
15e75aac0e2bfc82d59cc59142b0f8aa652695c3 | strahinjakupusinac/python_playground | /src/directory_printer.py | 658 | 3.59375 | 4 | '''
Created on Sep 29, 2013
@author: Strahinja
'''
import os
from os.path import isdir, isfile, join
def printDir(path, depth):
directories = []
files = []
for child in os.listdir(path):
if isdir(join(path,child)):
directories.append(child)
elif isfile(join(path,child)):
... |
3592e1ec48d012c39cbd5a3e99a46e2c2dd557c2 | jimroma/dataquest | /IntroFunctions/07.py | 461 | 3.546875 | 4 | f = open("story.txt", 'r')
story_string = f.read()
clean_chars = [",", ".", "'", ";", "\\n"]
# Previous code for clean_text().
def clean_text(text_string, special_characters):
cleaned_string = text_string
for clean_char in special_characters:
cleaned_string = cleaned_string.replace(clean_char,"")
c... |
d8b4d0b6b476b8273f58df12fcf9703faf5d9448 | Saulnier/FWI-Demo-Git | /pig-latin.py | 320 | 3.84375 | 4 | pyg = 'ay'
original = input('Enter a word:') #WORD
if len(original) > 0 and original.isalpha(): # adding alpha char
word = original.lower() #word
first = word[0] #w
new_word = word + first + pyg #wordway
new_word = new_word[1:len(new_word)] #ordway
print (new_word)
else:
print ('please type one word') |
220ede130fce5c8095cde6064f6bd770c392fcab | pranit14/Movies-Suggester | /Movies Suggester/main.py | 2,029 | 3.5625 | 4 | import tkinter as tk
data = open("Data.csv","r")
movies = []
for movie in data.readlines():
movies.append(movie.split(","))
for movie in movies: #to bring all genres at one index
temp = ""
for i in movie[4:]:
temp=temp + "," + str(i)
for i in movie[4:]:
movie.remove(i)
movie.append(temp[1:])
... |
37b4d3362ef0f5199af320f6d3a79f748bff46b9 | Ebele-Abolo/Identity | /untitled3.py | 861 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 30 15:07:21 2021
@author: joyab
"""
from tkinter import*
root = Tk()
root.title("Identity Card")
root.geometry("300x400")
label_id = ()
label_name = ()
label_dob = ()
label_pin= ()
label_address=()
label_vehicle=()
def function_identity():
label... |
17096b5c716844a7906068c588e2091e5c356768 | 0x1za/algorithms_in_python | /03_linked_list.py | 1,484 | 4.3125 | 4 | class Node:
def __init__(self, data):
self.data = data # Assign the data here
self.next = None # Set next to None by default.
class LinkedList:
def __init__(self):
self.head = None
# Display the list. Linked list traversal.
def display(self):
temp = self.head
d... |
9fa3d9ff22760fd01db9528a1e5326c5ae90175e | cemalsenel/pythonQuestions | /day20.py | 2,019 | 3.9375 | 4 | print((lambda x,y : (x+y)/2)(5,3))
num1=[9,6,7,4]
num2=[3,6,5,8]
print(list(map(lambda x,y:(x+y)/2, num1,num2)))
words1=["you","much","hard"]
words2=["i","you","he"]
words3=["love","ate","works"]
sentence = list(map(lambda x,y,z : (x+" "+y+" "+z),words2,words3,words1))
print(sentence)
first_ten = [0, 1, 2, 3, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.