blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c489fc42648ea2da24148b12fd6a08c22015ca6f | tommydo89/CTCI | /5. Bit Manipulation/conversion.py | 399 | 4.53125 | 5 | # Write a function to determine the number of bits you would need to flip to convert
# integer A to integer B.
def conversion(A, B):
num = A ^ B # we xor A and B in which the number of 1 bits in the resulting number will indicate the number of bits we need to flip to convert A to B
bits_to_flip = 0
while num != 0... |
a71b44bcf240553a0465b0e52376a57247230366 | Wireframe-Magazine/Code-the-Classics | /soccer-master/soccer.py | 54,019 | 3.578125 | 4 | import pgzero, pgzrun, pygame
import math, sys, random
from enum import Enum
from pygame.math import Vector2
# Check Python version number. sys.version_info gives version as a tuple, e.g. if (3,7,2,'final',0) for version 3.7.2.
# Unlike many languages, Python can compare two tuples in the same way that you can compare... |
5de8b683cb8c9dd4222945206efeb5abde0fcbee | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_97/1833.py | 748 | 3.5625 | 4 | #!/usr/bin/env python
import sys
def debug(*args):
""" Debug function"""
# print args
def recycled(n, m):
n, m = str(n), str(m)
if n == m:
return False
if len(n) != len(m):
return False
if n.startswith("0") or m.startswith("0"):
return False
for i in range(1, len(n)):
recycled_n = n[-i:] + n[0:len(n) -... |
fe8e91681edd5e75fc184df456675d100cc18ab5 | ZakirovRail/GB_Python_Faculty | /1_quarter/Python_Algos_alexey_petrenko/Lesson_3/HW_3/task_3_change_pos_min_max.py | 1,533 | 3.8125 | 4 | import random
# LENGTH = 5
# START = 0
# STOP = 100
#
# random_list = [random.randint(START, STOP) for i in range(LENGTH)]
# print(random_list)
#
# max_num = 0
# min_num = random_list[0]
#
# for i in random_list:
# if i > max_num:
# max_num = i
# if i < min_num:
# min_num = i
#
# print(f'The ma... |
cb7f0ddc0074cbf79aa15a400e153ebc1e917e93 | surajshardade/Python_Assign | /longest_word_in_list.py | 433 | 4.34375 | 4 | def find_longest_word(list1):
long_word=""
max_len=0
for word in list1:
count=0
for ele in word:
count+=1
if count>max_len:
max_len=count
long_word=word
return max_len
if __name__=="__main__":
list_of_words=eval(input("Enter li... |
89e7d0de4b2b7aefc22c268e0673b2105afb9a06 | AcaciaCalegari/lista01UFRJpython | /acaciacalegariaula01.py | 2,580 | 3.75 | 4 | #Lista01
#Nome:AcaciaCalegari
#1- Funcao q calcula a area de um retangulo
def retangulo (a,b):
"""Dado dois valores calcula a Area do retangulo"""
return a*b
#2- Funcao que calcula a area da superf́iciede um cubo que tem c por aresta
def cubo (c):
"""Calculando a area da superfıcie do cubo q... |
a474df413b1d6bf20c39765b4d8704bca076f14b | skinder/Algos | /PythonAlgos/Valid_Parentheses.py | 1,400 | 4 | 4 | '''
https://leetcode.com/problems/valid-parentheses/
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Exa... |
d42b4e3c12481e071bec28048c69c16f523f83c6 | huyquat/huyquat2 | /7.py | 99 | 3.578125 | 4 | S=input('Nhap chuoi:')
S1=S.split(' ')
S2=''.join([i for i in S if not i.isdigit()])
print(S2)
|
0231a5dde72b34a4ea7d48dc0f850bfd4e933712 | holothuria/python_study | /応用編/41_csvファイルの読み書き/モジュール/02_CSVファイルの読み込み.py | 390 | 3.734375 | 4 |
import csv
csv_file = open('./python.csv', 'r', newline='')
reader = csv.reader(csv_file)
for row in reader:
print('-------------------')
for cell in row:
print(cell)
csv_file.close()
csv_file = open('./python_1-4.csv', 'r', newline='')
reader = csv.reader(csv_file)
for row in reader:
print('----------... |
e837d3d73052b5daffe1d68e70544c1a934f3bc3 | 1MiguelSantiagoR1/LaboratorioFunciones | /main3.py | 348 | 4.125 | 4 | def a_power_b(a,b):
resultado=pow(a,b)
return resultado
a=2
b=2
contador=0
while a > 0:
a=int(input("Ingrese un numero:"))
b=int(input("Ingrese otro numero: "))
print(a_power_b(a,b))
contador=contador+1
if a == 0:
print("A tomo valor de cero, el ciclo termino con un total de",contado... |
62fa2a9d30a5107bec1d744a4bd85f2c106e2d7b | lealb/leetcode | /python/4_Median_of_Two_Sorted_Arrays.py | 467 | 3.78125 | 4 |
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Follow up: The overall run time complexity should be O(log (m+n)).
"""
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
pass
if __name__ =... |
8a7ddc4299b8881d77cc31a1c887e71e3edc2d26 | vprusso/6-Weeks-to-Interview-Ready | /module_2/python/num_islands.py | 2,987 | 3.96875 | 4 | """
Title: Number of islands.
Problem: Given a 2d grid map of '1's (land) and '0's (water), count the number
of islands. An island is surrounded by water and is formed by connecting
adjacent lands horizontally or vertically. You may assume all four edges of the
grid are all surrounded by water.
Execution: python num_... |
e4c449091a9aa0f02c8574b1518153289ca3477c | TBKelley/kaggle-allstate-tk | /ALLSTATE/DataLoad.root/DataLoad/TimeStamp.py | 901 | 3.765625 | 4 | import datetime as dt
class TimeStamp(object):
"""
Encapulates TimeStamp processing.
"""
def __init__(self, name=None):
self.__startDateTime = dt.datetime.now()
if (name is None):
self.__name = ''
else:
self.__name = ' ' + name
@property
def Star... |
2642d5e6a54f584f4fda61832aebaf3377d7bb56 | wangpeibao/leetcode-python | /easy/easy849.py | 1,853 | 3.84375 | 4 | '''
849. 到最近的人的最大距离
在一排座位( seats)中,1 代表有人坐在座位上,0 代表座位上是空的。
至少有一个空座位,且至少有一人坐在座位上。
亚历克斯希望坐在一个能够使他与离他最近的人之间的距离达到最大化的座位上。
返回他到离他最近的人的最大距离。
示例 1:
输入:[1,0,0,0,1,0,1]
输出:2
解释:
如果亚历克斯坐在第二个空位(seats[2])上,他到离他最近的人的距离为 2 。
如果亚历克斯坐在其它任何一个空位上,他到离他最近的人的距离为 1 。
因此,他到离他最近的人的最大距离是 2 。
示例 2:
输入:[1,0,0,0]
输出:3
解释:
如果亚历克斯坐在最后一个座位上,他离最近的人有 ... |
328acb4a273d49ec0f912e0c5588bcda16d92764 | sca4cs/Graphs_Python | /projects/graph/src/graph_demo.py | 1,446 | 3.796875 | 4 | #!/usr/bin/python
"""
Demonstration of Graph and BokehGraph functionality.
"""
import random
from sys import argv
from graph import Graph
from draw import BokehGraph
def main(num_vertices=None, num_edges=None, connected=None):
if num_vertices is None:
num_vertices = random.randint(1, 20)
else:
... |
5ceb1383610c072a41ff14b9c997118efa500c2c | VaishnaviReddyGuddeti/Python_programs | /Python_Sets/accessitems.py | 540 | 4.5625 | 5 | # You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
# But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
# Loop through the set, and print the values:
thisset = {"apple", "banana",... |
428b742eb17dfb9ed19c76d77b55860416e12951 | nthiery/pypersist | /pypersist/diskcache.py | 5,685 | 3.59375 | 4 | """Persistent memoisation backend that saves results in the local file system.
The `persist` decorator takes a `cache` argument, which details what sort of
backend to use for the cache. If this string begins with 'file://', or if no
`cache` is specified, then a *disk cache* is used, which saves computed results
to a ... |
4726db59dcb4ec951eec38d9dd9bb8fa39bf5387 | ntongha1/Leetcode_Problems | /largest_time_for_given_digits.py | 1,860 | 4 | 4 | """
Largest Time for Given Digits
Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5. If no valid time c... |
469f5c2183cf9cc8a4e01f7db0d46dd91652255d | GDevigili/A1LP-Valhalla-cinema | /trabalho-extra/main.py | 4,207 | 3.59375 | 4 | import os
'''
chave1:elemento1
chave2:elemento2
chave2:elemento3
chave4:elemento4
'''
class FileDict(dict):
"""A classe FileDict define um dicionário com funcionalidade de arquivos"""
"""
File based dict sub-class
filepath [str]: path to the core file of the dict
"""
#defines the separato... |
04b4a28b79286f0d68a8df2a744528101ba270d3 | sudakevych-andrii-itea/practice | /homework2/main.py | 2,540 | 3.515625 | 4 | # Создать консольную программу-парсер, с выводом прогноза погоды. Дать
# возможность пользователю получить прогноз погоды в его локации ( по
# умолчанию) и в выбраной локации, на определенную пользователем дату.
# Можно реализовать, как консольную программу, так и веб страницу.
# Используемые инструменты: requests, bea... |
0e88ee40058d2dbbf29868eb97d54b57698716d2 | aaronspurgeon/graphs | /projects/ancestor/ancestor.py | 1,548 | 3.8125 | 4 | from util import Stack, Queue
def get_parents(ancestors, child):
results = list()
for item in ancestors:
if child == item[1]:
results.append(item[0])
return results
def earliest_ancestor(ancestors, starting_node):
child_list = set()
for item in ancestors:
child_list.a... |
bc98bb4cc976d9a1cfe3fe5a03ede21e3017cd45 | zhyu/leetcode | /algorithms/reverseLinkedList/reverseLinkedList.py | 678 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
if head is None:
return head
helper = ListNode(0)
... |
ed8adcab7145773d4d932a07dc51b7768762885d | benbendaisy/CommunicationCodes | /python_module/examples/92_Reverse_Linked_List_II.py | 1,669 | 4.1875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
from typing import Optional
class Solution:
"""
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of th... |
b8f2d4975f70e3976a379b9ee98b81cd3710b04b | Aymerolles/Workshops | /DeepLearningWithPython/DeepLearningWithPython_Part2.py | 2,322 | 3.53125 | 4 |
# coding: utf-8
# # Load the dataset
# In[1]:
#import the libraries
import keras
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
# load the image data
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
... |
b3c89c5823efd26ae19418e7d3e487c37e2ca75f | arvind-iyer/easyweb | /src/easyweb/core.py | 1,550 | 3.65625 | 4 | import inspect
def classmethods(class_object):
"""Takes an object and returns a list of names of all the methods
in that class
:param class_object : instance of any class in python
:return : list of method names as strings
"""
fn_tuple_list = inspect.getmembers(class_object, predicate=inspect.... |
da553be96ec1161c1cb8ef4925c0dbe1200907c3 | aawilson/aloneinspace | /lib/python/aloneinspace/poly.py | 667 | 3.890625 | 4 | class Rect(object):
def __init__(self, x, y, w, h):
self.x1 = x
self.y1 = y
self.x2 = x + w
self.y2 = y + h
def center(self):
return (self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2
def intersects(self, other):
return (
self.x1 <= other.x2 and
... |
986049fc18c609c8128c9ef6ba6b385b08e8aae9 | majcn/projectEuler | /4.py | 137 | 3.59375 | 4 | #!/usr/bin/python2
import itertools as it
print max([x*y for x,y in it.product(range(1000), range(1000)) if str(x*y) == str(x*y)[::-1]])
|
c24b0879a5fce5dbf0913d2df7ba75786fee0c99 | jwellton/Python-solutions-programming-exercises | /Module 6/Golf_Scores6_10_1.py | 686 | 4.09375 | 4 | # Golf_Scores6_10_1
# The Springfork Amateur Golf Club has a tournament every weekend.
# The club president has asked you to write two programs:
# 1. A program that will read each player’s name and golf score
# as keyboard input, then save these as records in a file named golf.txt.
# Each record will have a field for... |
9aac6490db83131aabfc8a73fb4b0e359c63364b | rsmonteiro2021/mathematic | /right_triangle/right_triangle.py | 440 | 3.578125 | 4 | # Módulo que define as funções 'area_triangulo' e 'hipotenusa' para calcular a área de um triângulo Retângulo:
# autor: Roberto dos Santos Monteiro
def area_triangulo_retangulo(base, altura):
"""Devolve a área de um triângulo retângulo"""
area = base * altura/2
return area
def hipotenusa(base, altura):
... |
fb87d8791f73b714d90f92bf73242bf9d4a4005c | wildenali/Python3_Basics | /31_Eksternal_Package/31_Eksternal_Package.py | 724 | 3.53125 | 4 | # Cara menggunakan eksternal package
# 1. python sudah terinstal
# 2. koneksi internet
# 3. dependency
# Contoh nya disini akan meng install package numpy (numerical python)
# ================ coba numpy ================
# import numpy as np
#
# # cara menggabungkan list biasa aja
# a = [1,2,3,4]
# b = [5,6,7,8]
# ... |
bc911dc3b893affd91f20a1ec70f27c7c89bb54b | TPLxxA/DataProcessing | /Homework/Week_4/convertCSV2JSON.py | 1,163 | 3.640625 | 4 | # Casper van Velzen
# Minor programmeren / Data_processing
# 11030275
# converts csv files to json format
#
import csv
import json
# remember lists for later
data = []
data2 = []
final_data = []
# open data file put dict with data in list
with open('Linguistic diversity index.csv', 'r') as csvfile:
rawdata = csv.re... |
d54fd3084619657b30a83cb67a6a89d087a6977a | mkhoshpa/Algorithms-DataStructure | /Mergeklist.py | 4,497 | 3.609375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.count = 1
self.left, self.right = None, None
def BSTInsert... |
81cf77ca51b31a39ad259e59e3352c19e7cebdaf | GlebBorovskiy/TMS_home_work | /work6.py | 906 | 4.21875 | 4 | #Написать функцию, подсчитывающую сколько раз пользователь ввел каждую строку. Пользователь вводить одну строку за раз. Каждый раз счетчик ввода этой строки увеличивается на 1. Если пользователь ввел строку "exit", программа завершается и выводит статистику введенных строк. Счетчики хранить в dict
def string_counter():... |
939ae9c31a06665ca3289439f5be9e1a3453248f | lucasrafaldini/DataScience | /Projects/Random_Quote_Selector/quote_selector.py | 599 | 3.59375 | 4 | #código incompleto
import pandas as pd
column_separator = ";"
dtype_dic={'Quote':str,'Author':str,'Genre':str}
file= pd.read_csv('/media/removable/CHROMECARD/GitHub/DataScience/Projects/Random_Quote_Selector/quotes_all.csv', dtype=dtype_dic, encoding='utf-8', sep=column_separator, engine='python', header=None)
pr... |
e5b6069412e0003b17a2e6416e67475c97206252 | annabe11e/Python_Data_Visualization | /Python Data Visualization .py | 4,834 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# A survey was conducted to gauge an audience interest in different data science topics, namely:
#
# Big Data (Spark / Hadoop)
# Data Analysis / Statistics
# Data Journalism
# Data Visualization
# Deep Learning
# Machine Learning
# The participants had three options for each topi... |
344047d036969a7a8f07df6cbae4ab3d75e28de0 | sp4ghet/comp | /abc149/c.py | 302 | 3.84375 | 4 | from math import ceil, sqrt
n = int(input())
if n == 2:
print(2)
exit()
n = n+1 if n % 2 == 0 else n
notPrime = True
while notPrime:
notPrime = False
for i in range(2, ceil(sqrt(n))):
if n % i == 0:
n += 2
notPrime = True
break
print(n)
|
7d33c2473766eb4341ecd30a2e147835c26fde37 | lluviaHR/311ComplainsExploration | /TopComplaints.py | 1,240 | 3.84375 | 4 | # break complaints into different complaint types, and
# output one complaint type per line, followed by the number of complaints of
# that type.
# Output the items ordered by the greatest to lowest number of complaints.
#
# e.g. output:
# Street Condition with 450 complaints
# Highway Sign - Damaged with 421 complaint... |
8c9c059b82d4dcd2863177a27c65482c8dec2abc | hetdev/hackerrank-solutions | /ginorts.py | 564 | 3.796875 | 4 | n = list(input())
lowers = []
uppers = []
nums_odd = []
nums_even = []
nums_zeros = []
for word in n:
if word.islower():
lowers.append(word)
elif word.isupper():
uppers.append(word)
else:
if int(word) % 2 == 0:
nums_even.append(str(word))
elif int(word) == 0:
... |
8ec02c73e100b30348da4f0bae66bff11e0dcf3d | pmayd/python-complete | /code/exercises/words_stats.py | 492 | 4.25 | 4 | import doctest
def word_stats(words: list):
"""Write a function that takes a list of words (strings). It should return a tuple containing three integers, representing the length of the shortest word, the length of the longest word, and the average word length.
Examples:
>>> word_stats(['test'])
(4, 4,... |
c1ff2c450b8b1020d7b6c7f8ab4b91816905bb88 | Isabelppz/FSDI111-Lab1 | /intro.py | 625 | 4.1875 | 4 |
print("Hello world")
#data types
name="Isabel"
last="P. Perez"
age=34
found=False
average=2.34
print (name)
print (average)
print (found)
#operations
print(21 + 21)
print(100 - 50)
print(12 * 321)
print(100 / 10)
print(10 % 3) #%=modulus operator(gives the residue)
print(name + name)
print(ag... |
cf2f4bbc8ebaa14ac38a07c878a525b327e38efb | Baidaly/datacamp-samples | /6 - introduction to databases in python/using alias to handle same table joined queries.py | 1,102 | 3.953125 | 4 | '''
Often, you'll have tables that contain hierarchical data, such as employees and managers who are also employees. For this reason, you may wish to join a table to itself on different columns. The .alias() method, which creates a copy of a table, helps accomplish this task. Because it's the same table, you only need ... |
27cf15d1470dcb3a7a895b836c2cf59918d044db | alexbispo/sala-do-templo | /fibonacci/python/solucao.py | 684 | 3.9375 | 4 | #*-* coding: utf-8 *-*
"""
Imprima os primeiros números da série de Fibonacci até passar de 100. A série de Fibonacci é a seguinte: 0, 1, 1, 2, 3, 5, 8, 13, 21, etc... Para calculá-la, o primeiro elemento vale 0, o segundo vale 1, daí por diante, o n-ésimo elemento vale o (n-1)-ésimo elemento somado ao (n-2)-ésimo ele... |
0b81df2b602ee90edc1cdad356d76fdfa149b78b | wangjiaz/fxrules | /forex-emu.py | 7,781 | 3.625 | 4 | import random
import sys, os
class Account (object):
""" account is the money management unit of my forex game """
def __init__ (self, base, append_capital, growth, unit_ratio, bonus_ratio, bonus_level_gap, name):
self.base = base
self.append_capital = append_capital
self.growth = growth
self.unit... |
1cd63bdffd65f078073b2b7339ab46e482a1e617 | angeloc/github-learning | /angelo/problem_12.py | 839 | 3.953125 | 4 | import time
import math
def count_factors(num):
# One and itself are included now
count = 2
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
count += 2
return count
def triangle_number(num):
return (num * (num + 1) // 2)
def divisors_of_triangle_number(num):
... |
4687a56bc3d2e9333c965b695bc864634efac3a7 | Pratham82/Python-Programming | /Practice_problems/Edabit/Get sum of people's budget.py | 698 | 3.75 | 4 | # Get Sum of People's Budget
# Create the function that takes a list of dictionaries and returns the sum of people's budgets.
# Examples
# get_budgets([
# { "name": "John", "age": 21, "budget": 23000 },
# { "name": "Steve", "age": 32, "budget": 40000 },
# { "name": "Martin", "age": 16, "budget": 2700 }
# ]) ➞ ... |
bebf16db3aac1d34ded420f38ea17a8e5a697790 | Uche-Clare/python-challenge-solutions | /Imaobong Tom/Phase 1/Python Basic 1/Day 3/10.py | 253 | 4.0625 | 4 | def multiple_string(string, number_of_times):
result = ""
if number_of_times <= 0:
print("input a positive integer")
for i in range(number_of_times):
result = result + string
return result
print(multiple_string("cup",0))
|
55cf0f807c4e9b907284fe85f7eca09c4970e3e0 | physimals/vb_tutorial | /code/svb_gaussian.py | 13,948 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Stochastic Variational Bayes
# =======================
#
# This notebook implements Example 1 from the FMRIB tutorial on Variational Bayes II: Stochastic Variational Bayes ("fitting a Gaussian distribution).
#
# We assume we have data drawn from a Gaussian distribution with tr... |
d6d23b833d3930816cfd68901c18fd2df2480df2 | bekir96/BOUN_PROJECTS | /CMPE493/Assignment1/damerau_levensthein.py | 6,037 | 4 | 4 | import sys
'''
function damerau_levenshtein_distance takes two input string,(s,t) and calculates
Damerau Levenshtein distance and returns it, the corresponding edit table and the
sequence of operations needed to transform the first string into the second one.
'''
def damerau_levenshtein_distance(s, t):
... |
82659861ff769914b950f3ac06c17fe0065df3be | nicetai/2017 | /pythontest/pythontest100/test01.py | 544 | 3.5625 | 4 | # -*- coding: utf-8 -*-
#第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
import random,string
forSelect = string.ascii_letters + "0123456789"
def generate(count,length):
#count = 200
#length = 20
for x in range(count):
Re = ""
for y in range(leng... |
aeceb2c41d68334e26f25a66cc9ecc61ac97adb6 | Denysios/Education- | /Python/Prep/les_4-task_3.py | 903 | 3.90625 | 4 | # Игра сражение
# запрос имени пользователя
player_name = input('Введите имя игрока')
# создание словаря игрока
player = {
'name' : player_name,
'health' : 100,
'damage' : 50,
'armor' : 1.2
}
# запрос имени врага
enemy_name = input('Введите имя врага')
# создание словаря врага
enemy = {
'name' : en... |
d66c07f28650448aa2fe1cf542e7b40b7ebdcd29 | MeghaSajeev26/LuminarmarchMorning | /decorators/exceptionHandling.py | 206 | 3.9375 | 4 |
num1=int(input("enter num1"))
num2=int(input("enter num2"))
try:
res=num1/num2
print(res)
except Exception as e:
print(e.args)
#Exception
#/by 0
# index out
#filenotfound
#type Error
|
8d6a0e81b8eb5b48e08e3765ab01dc6cdaa8b1bb | PacktPublishing/Learn-Python-3-from-Scratch | /CODES/S11/1-filedemo1.py | 242 | 3.59375 | 4 | """
File I/O
'w' -> Write-Only Mode
'r' -> Read-only Mode
'r+' -> Read And Write Mode
'a' -> Append Mode
"""
my_list = [1, 2, 3]
my_file = open("firstfile.txt", "w")
for item in my_list:
my_file.write(str(item) + "\n")
my_file.close() |
d3e9ddcafff01d80c497bbb4a96c43cf98a4a976 | HarleyB123/python | /session_1/answers/D5.py | 588 | 4.15625 | 4 | # D5 - Ask the user for 2 different numbers, if the total of the two numbers
# is over 21, print "Bust" otherwise print "Safe"
# Ask for user input and cast to integers
number_1 = int(input("Please enter your first number: "))
number_2 = int(input("Please enter your second number: "))
# Work out the total of the 2 nu... |
d38b23e2e6b9aa134d1205cbe00b4234d477a01a | thals7/BOJ | /수학1/2839.py | 210 | 3.609375 | 4 | import sys
n = int(sys.stdin.readline())
five = 0
three = 0
while n > 0:
if n % 5 == 0:
five += n // 5
break
three += 1
n -= 3
if n < 0:
print(-1)
else:
print(five+three) |
a4ed231bcd6e36fe1cb17e71126973ff4e43a118 | vinod-designer1/competitive-programming | /Sorting/sort.py | 1,084 | 3.984375 | 4 | class Sort(object):
"""docstring for Sort"""
def __init__(self, items):
super(Sort, self).__init__()
self.items = items
self.itemsLen = len(self.items)
def insertionSort(self):
for i in range(1, self.itemsLen):
j = i
while j > 0 and (self.items[j] < self.items[j-1]):
self.swap(j, j-1)
j = j-1
... |
0583a08ece91110743ed3356e484918672b0f796 | clicianaldoni/aprimeronpython | /chapter8/compute_prob.py | 804 | 3.75 | 4 | # Exercise 8.2
# Probability of getting a number (0.5, 0.6)
from random import random
def prob(start, stop, N):
i = 0 # N must be positive
match = 0
while i <= N:
ran = random()
if ran > start and ran < stop: # Not including the start and stop point
match += 1
i += 1
... |
f9219084fee7abf1c354a71a9df2767da305cbea | uhlissuh/MITopencourseware-CS6.00 | /problemset0.py | 134 | 3.59375 | 4 | birthday = raw_input('What is your date of birth?')
lastName = raw_input('What is your last name?')
print (birthday + " " + lastName)
|
d75980bb99262efbf0080b4269f8c666ef73eec7 | nunes-moyses/Projetos-Python | /Projetos Python/pythonexercicios/des026.py | 149 | 3.859375 | 4 | n = str(input('Digite seu nome: '))
if n == 'Moysés':
print('Que nome lindo!')
else:
print('Seu nome é tão normal')
print('Bom dia,', n)
|
11736e959f8b881431fc376b7d0a6627875d5e04 | kucherskyi/train | /lesson05/task05.py | 325 | 3.765625 | 4 | #!/usr/bin/env python
"""
Print a number of numbers in a file; each number shall count only once
(e.g. 1234 shall count only once, not 4 times).
"""
import re
with open('alice.txt', 'r') as alice:
numbers = 0
for line in alice:
numbers += len(re.findall(r'\d+', line))
print '{} numbers'.format(numb... |
976cb9ac53c9c69d4cc55f9a1f0e763ec4d8e3f5 | vtjeng/coding-contests | /kick_start/2021/A/checksum/checksum.py | 1,662 | 3.6875 | 4 | #!/usr/bin/env python3
def get_vals(s):
return list(map(int, s.strip().split()))
def find_partition(x, par):
if x == par[x]:
return x
par[x] = find_partition(par[x], par)
return par[x]
def union(x, y, par):
"""Join the sets containing elements x and y.
Returns
-------
bool... |
fce656f94a2b22a22fc1d072b1fcca0564db7ba6 | SergeyZybarev/GH | /2_1.py | 203 | 3.78125 | 4 | z = 58375
print("Maximum number in a given number ", z, end = " ")
max_digit = 0
while z%10 > 1:
digit = z%10
z //= 10
if digit > max_digit:
max_digit = digit
print(" - ", max_digit)
|
74e5ab94e0c033f0e8dc6867cb82d2a3c26ed6f5 | elunna/eular_python | /birthdays.py | 800 | 3.671875 | 4 | import random
import logging
BIRTHDAY = 1
PEOPLE = 25
PARTYS = 100000
SAME_BIRTHDAYS = 0
LOG_FILENAME = 'test.log'
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG)
if __name__ == "__main__":
print('~~~~~~~~~~~~~~~~~~~~~\n')
for i in range(PARTYS):
birthdays = [rando... |
9301d40f7db83a327cb29d28d0a027881be233f6 | rebkwok/adventofcode | /2022/day4.py | 1,387 | 3.546875 | 4 | from argparse import ArgumentParser
from utils import read_as_list
def read_input(inputfile):
return read_as_list(inputfile)
def convert_assignment_pair_ranges(input):
pairs = []
for line in input:
elf1, elf2 = [elf.split("-") for elf in line.split(",")]
elf1_range = list(range(int(elf... |
355651536f63a043208b9744ee79b1e219e23c4f | dawitys/Competitive-Programming | /week1/triangle1.py | 74 | 3.546875 | 4 | def print_triangle(n):
for i in range(1, n+1, 1):
print(i*'*') |
a082bec27a3ddd3738e1b596642ffc41241ad0b5 | dowski/scoreboard | /plugins/smallboard/smallboard/control.py | 1,745 | 3.5625 | 4 | """Low-level support for controlling the two digits of the 7-segment display.
"""
from gpiozero import LED
DIGITS = {
# 7-segment pins
# -----------------
# 4 3 2 1 8 7 6 5
# -|-------------|-
# | |
0: [1,1,1,0,1,1,0,1], # 0
1: [1,0,0,0,1,0,0,0], # 1
2: [1,1,0,1,0,... |
9825c51621b7d31921c28c32c6527a768e96a257 | AndyFlower/zixin | /python/pyfiles/numpy_update.py | 775 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 08:44:58 2020
@author: sangliping
"""
import numpy as np
x = np.arange(8)
print(x) #[0 1 2 3 4 5 6 7]
print(np.append(x,8)) #是在副本上添加 [0 1 2 3 4 5 6 7 8]
print(np.append(x,[9,10])) #[ 0 1 2 3 4 5 6 7 9 10]
print(np.insert(x,1,8)) #[0 8 1 2 3 4 5 6 7]
x[3]... |
f57b858d69743b4173878579549af46c79abee8d | BlueIrisEagle/Huffman_Coding | /app.py | 541 | 3.609375 | 4 | from Huffman.compress import compress
from Huffman.decompress import decompress
import os
print("\t\t\t\t\t\t#### Huffman Coding App ####")
type = input("1- Compress File\t2- Decompress File\t3- Compress Folder\t4- Decompress Folder\t")
filePath = input("Please enter file name inside the project folder\t")
if(int(typ... |
b8891a8140f4f728ef62e49e8007377d7f26f488 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/801-1000/000938/000938.py | 1,059 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def rangeSumBST(self, root, low, high):
"""
:type root: TreeNode
:ty... |
b847dcef88b82481fd109dd040041ea121c4217e | NiramBtw/project_euler | /Problem 10 - Summation of primes.py | 425 | 3.890625 | 4 | """
project euler 10
by: Nir
Summation of primes
"""
N = 2000000
import math
def IsPrime(n):
for i in range(2, int(math.sqrt(n)) + 1, 1):
if n % i == 0:
return False
return True
def main():
primes = [2]
for n in range(3, N, 2):
if IsPrime(n):
... |
245156de80747a033f3790c5208728dd8775870f | jemtca/CodingBat | /Python/List-3/max_mirror.py | 887 | 4.3125 | 4 |
# we'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order
# for example, the largest mirror section in {1, 2, 3, 8, 9, 3, 2, 1} is length 3 (the {1, 2, 3} part)
# return the size of the largest mirror section found in the... |
97e6140c69f7e2c4736abb2a72edc3386c97497c | xli1110/LC | /Others/Amazon. Encode String.py | 939 | 3.71875 | 4 | """
Encode String: Input -> Output:
aaaab -> 4xab,
aabb -> 2xa2xb,
abcccc -> ab3xc,
aa -> a != 2xa
x -> x != x
"""
def encode(s):
if not s:
raise Exception("Empty String")
res = ""
ch = s[0]
num = 1
flag_unique = True
for i in range(1, len(s)):
if s[i] == ch:
n... |
ee37c326f35fe15b77aa51079a0bde3a6517d154 | daimengqi/Coding4Interviews-python-DMQ | /Coding4Interviews-python-DMQ/剑指offer/063-数据流中的中位数/code.py | 1,230 | 3.671875 | 4 | class Solution:
def __init__(self):
self.sortedList = []
def Insert(self, num):
# write code here
n = len(self.sortedList)
self.sortedList.append(num)
while n != 0:
if self.sortedList[n] < self.sortedList[n-1]:
self.sortedList[n], self.sortedLi... |
2624e062530674903011e535e316be083524b287 | afacio/System-plikow | /Interface.py | 3,880 | 3.5625 | 4 | import os
import File
import Directory
import Tree
import Function
class Interface():
def __init__(self):
self._MENU = "\nAvailable commands:" \
"\n- ls\n- tree\n- pwd\n- cd up\n- cd down" \
"\n- make dir\n- ren dir\n- del dir" \
"\n- make file... |
b5b5a867444e143b9bb621110ce39f77b92f2621 | sbd2309/Adv.Python | /DictionariesandMaps.py | 460 | 3.53125 | 4 | n=int(input())
d={}
for i in range(0,n,1):
s=input()
name=s.strip().split(' ')[0]
pnum=s.strip().split(' ')[1]
d.update({name:pnum})
l=[]
takename='Author:SoumyaDutta'
for i in range(0,n,1):
takename=input()
if takename!='':
l.append(takename)
for i in l:
flag=0
for key,value in ... |
c72b8e05b92daf7b395b5d8eeb135b5edce6380e | SeanLeCornu/Coding-Notes | /1. Python - Python Programming Textbook - Notes/Chapter 7/7.3 Shelves.py | 754 | 3.875 | 4 | # We can shelve lists together in a file
# the shelf key acts like a dictionary, importantly the shelf key can only be a string
import pickle
import shelve
print("\nShelving lists.")
s = shelve.open("pickles2")
s["variety"] = ["sweet", "hot", "dill"]
s["shape"] = ["whole", "spear", "chip"]
s["brand"] = ["Claussen"... |
f1243f9200312dd5693b80cf3f61f3dda5ab091e | DreEleventh/python-3-object-oriented-programming | /ch03/diamond2.py | 1,479 | 4.3125 | 4 | class BaseClass:
"""
Base class for demonstrating the diamond problem of multiple inheritance.
This time using calls to super(), which calls the next method in the
inheritance hierarchy. This is not necessarily the parent class, especially
in multiple inheritance situations.
"""
num_base_ca... |
b1e39d38cc1753220c15b001d3ab44de6ba4bf3a | kelr/practice-stuff | /leetcode/1161-maxlevelsumbinarytree.py | 1,777 | 3.765625 | 4 | from collections import deque
# BFS with levels to find the sum of each level.
# Return the smallest level that has the maximum sum
# O(N) time, N to BFS + N to find the max worst case when N == height of tree
# O(N) space, (N+1)/2 queue max elems if perfect tree which are the leaf nodes, N size of levelSums wors... |
2f98bbcfb9a0a2c30db4eec673956dcda1201fc1 | mannhuynh/Python-Codes | /python_codecademy/len_slice.py | 1,583 | 4.625 | 5 | """Len's Slice
You work at Len’s Slice, a new pizza joint in the neighborhood. You are going to use your knowledge of Python lists to organize some of your sales data."""
# To keep track of the kinds of pizzas you sell, create a list called toppings
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", ... |
5cd7d7e9bd06183cf04d7898c7412aef669e09bd | Parzival129/BackTrack-WIP- | /wikipedia_test.py | 1,366 | 3.734375 | 4 | # import all modules
import wikipediaapi
import time
# set language
wiki_wiki = wikipediaapi.Wikipedia('en')
page_py = wiki_wiki.page('Ready Player One')
print("Page - Exists: %s" % page_py.exists())
# Page - Exists: True
if page_py.exists() == True:
print ("THE BOOK EXISTS!")
elif page_py.exists() == False:
pri... |
2b1482abb3e0101a639f18e40022b61486d82536 | dolapobj/interviews | /Data Structures/Trees/InvertBinaryTree.py | 707 | 4.09375 | 4 | #Invert a Binary Tree
#Leetcode 226
"""
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Input:
1
/ \
2 3
Output:
1
/ \
3 2
"""
def invertTree(root):
if not root:
return
if root.left == None and root.righ... |
8dbd9ddde5f029865363ae6c06d68abb3af879c8 | keertipc7/SRFP_2021_Summer_Project_in_Statistical_Estimation | /Codes/LADsolvingAlgo.py | 5,448 | 3.953125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import random
print(" ")
print("______________________________________")
print("Step-Wise Algorithm")
print(" ")
#creating datapoints
X = np.ones((100,2)) # we are working in a 2d plane with 100 datapoints
for i in range(100): #x[:,0] is going to be =1 thrughout as ... |
8b5da5096dc945b658b0a75f817e7e5e8e0d5006 | omitiev/python_lessons | /python_tasks_basics/quiz_tasks/quiz_task_12.py | 1,532 | 3.5625 | 4 | # 12. Для проверки остаточных знаний учеников после летних каникул, учитель младших классов решил начинать каждый урок с того,
# чтобы задавать каждому ученику пример из таблицы умножения, но в классе 15 человек, а примеры среди них не должны повторяться.
# В помощь учителю напишите программу, которая будет выводить на... |
5543d2333d3c373ef9189fbf939e7b654a80f370 | Rodrigo-P-Nascimento/Python | /ex045.py | 1,288 | 3.703125 | 4 | from random import randint
from time import sleep
itens = ("Pedra", "Papel", "Tesoura")
computador = randint(0, 2)
print("""\033[33mSuas opções:\033[m
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] TESOURA""")
jogador = int(input("\033[33mQual a sua jogada?\033[m "))
print("JO")
sleep(1)
print("KEN")
sleep(1)
print("POOO!!... |
acdbae328d4470d480c2369c62c05a4c12514331 | kushal200/python | /Basic/ListOfpython/greatestNumber.py | 268 | 4.03125 | 4 | a=int(input("Enter the First Number:"))
b=int(input("Enter the Second Number:"))
c=int(input("Enter the Third Number:"))
if a>b>c:
print("%d is a Greatest Number" %a)
elif b>a>c:
print("%d is a Greatest Number" %b)
else:
print("%d is a Greatest Number" %c) |
3986fbc8058da5aa380a8492ac79092e29aae802 | aarhusdavid/CPSC408files | /CPSC 408/Project_Part_1/sqldb.py | 15,515 | 4.1875 | 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(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
conn.... |
2b093b85a151e13860b4d4c3a49d281e8fe0539c | zells/seven | /python/src/zells/TurtleZell.py | 4,582 | 3.65625 | 4 | import math
class TurtleZell(object):
def __init__(self, name, emit):
self.name = name
self.emit = emit
self.position = [0, 0]
self.angle = 90
self.segments = []
self.canvases = {}
print "Created Turtle " + name
def receive(self, signal):
if s... |
e41b0733d997b591f771dc5d53af81ad0f3bec83 | Pavlov83/Python | /AlgorithmsAndDataStructures with Projects/resources/Benjamin Baka Book/obejcts_types_expressions/flow_control_and_iteration.py | 105 | 3.90625 | 4 | x = 1
if x == 0:
print("x is zero")
elif x == 1:
print('True')
else:
print("Something else") |
ad13e47e840cd23efda61f98a6a7fc3524b83c2b | suraj19/Python-Assignments | /program14.py | 292 | 3.796875 | 4 | #Date: 28-07-18
#Author: A.Suraj Kumar
#Roll Number: 181046037
#Assignment 10
#Python Program to print the lowest index in the string where substring sub is found within the string.
str_1= input('Enter your String:')
str_2= input('Enter your Sub String:')
str_3= str_1.index(str_2)
print(str_3)
|
cedcb9005e26dc808fa3735154c9ac229a3e12e9 | jaythecaesarean/robot_moves | /robot_moves.py | 6,755 | 4.59375 | 5 | #!/usr/bin/python
# Filename: robot_moves.py
"""
This script simulates a robot moving on a 5 by 5 units tabletop
with the following commands:
PLACE X,Y,F --> Placing the robot to the location (x,y) and direction (f)
MOVE --> Moves the robot 1 unit forward unless if it's out of bounds
LEFT ... |
6be3255b0ccff0821f14f3e9d34c06d09f942def | peindunk/stu_project | /stu_main.py | 1,074 | 3.625 | 4 | import menu as m
import student_info as si
import sys
def main():
infos=[]
while True:
m.output_menu()
try:
choice = input('请选择功能\n')
except:
print('输入有误')
continue
if choice== 'q':
sys.exit()
elif choice == '1':
... |
44ede9e76c7f3221ed939791f714a56669cb8632 | Varoon3/NBA-Hackathon | /Basketball Analytics/plusminus.py | 8,640 | 3.625 | 4 | #!/usr/bin python3
import pandas as pd
import numpy as np
def process_match_lineups():
"""This function is used to make two dictionaries to a) hold unique match ups to track box scores
b) track players on the floor after each period
Returns:
league_matches: {
game_id: {
... |
3fd428d927c9c40abde221145b9e08bd308a6847 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/juan-alejandro-calzoncit-rodriguez/práctica-2/capítulo-9/9-4.py | 793 | 3.859375 | 4 | class Restaurant(object):
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_serverd = 0
def set_number_serverd(self,num):
self.number_serverd = num
def incremet_number_served(self, num):
... |
dfd2dca2811b7d67bea15ab1e2936bf23ba6ee4d | tx991020/MyLeetcode | /排序和搜索/快排.py | 2,269 | 3.890625 | 4 | from typing import List
import random
def quick_sort(a: List[int]):
_quick_sort_between(a, 0, len(a) - 1)
def _quick_sort_between(a: List[int], low: int, high: int):
if low < high:
# get a random position as the pivot
k = random.randint(low, high)
a[low], a[k] = a[k], a[low]
... |
dc2a0804f7e942846afd632acee327c12a2f268d | vermaarun/codingChallenges | /Strings/largest_permutation.py | 480 | 3.8125 | 4 | def largest_permutation(num):
num_array = [0] * 10
while num > 0:
digit = num % 10
num_array[digit] += 1
num = num / 10
print num_array
largest_number = []
for i in range(9, -1, -1):
largest_number += num_array[i] * [i]
print largest_number
return int(''.join(... |
876509f5e22b9260e7097914e5cf7bb7816b64fa | coderSuhaib/FizzBuzz | /FizzBuzz.py | 236 | 3.75 | 4 |
x = 3
y = 5
for count in range(1,101,1):
if count % x == 0 and count % y == 0:
print("FizzBuzz")
elif count % x == 0:
print("Fizz")
elif count % y == 0:
print("Buzz")
else:
print(count)
|
85758fce1820d89d8c8cb4c132d355aa4d251e7d | mmozuras/string-calculator-kata-python | /calculator_spec.py | 757 | 3.5 | 4 | from calculator import add
def describe_string_calculator():
def returns_0_for_empty_string():
assert add('') == 0
def returns_bare_numbers():
assert add('0') == 0
assert add('1') == 1
def adds_numbers():
assert add('1,2') == 3
assert add('1,10') == 11
def describe_delimiters():
def ... |
53e36949500bf8e2e228d94d8d8c9aca311f4edb | napoleonwxu/ProjectEuler | /004.py | 429 | 3.625 | 4 | def maxPalindrome_6digit():
half = 999
while half >= 100:
palindrome = half*1000 + (half%10)*100 + (half/10%10)*10 + half/100
factor = 999
while factor >= 100:
if palindrome%factor == 0 and palindrome/factor <= 999:
print palindrome, '=', factor, '*', palindro... |
28f0c3d83f901c1c5e32161a46fd4844763f42c4 | thekatt0/exercises | /exercise3.py | 174 | 3.9375 | 4 | list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
listSmall = []
for num in list:
if num < 5:
listSmall.append(num)
for smallNum in listSmall:
print(smallNum)
|
1efde29cb5f29cd8d366b2f1ccaa9941c7bfccf9 | LucasAngeloni/TpSoporte | /practico_01/ejercicio-03.py | 598 | 3.90625 | 4 | # Implementar la función operacion, donde:
# - Si multiplicar es True: devolver la multiplicación entre a y b.
# - Si multiplicar es False: devolver la division entre a y b.
# - Si multiplicar es False y b es cero: imprimir por consola "Operación no valida".
def operacion(a, b, multiplicar):
if multiplicar == True... |
e92d84a42ed18eaf444a3a4d8345347adf10d014 | xiaochaohasun/studyPythonSummary | /basic/args_group.py | 519 | 3.609375 | 4 | #!/usr/bin/env python
def get_args(*args): #tuple
print args
#result
# ()
# ('abc',)
# (10, 20, 30)
def get_kwargs(**kwargs): #dict
print kwargs
#result
# {}
# {'age': 23, 'name': 'bob'}
def get_info(name,age):
print '%s is %s years old.' % (name,age)
if __name__ == '__main__':
get_args()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.