blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c8b2f991f2127ea1b2de3133b4b4ff625c2b6d6f | kelpasa/Code_Wars_Python | /6 кю/Error correction #1 - Hamming Code.py | 965 | 4.46875 | 4 | '''
Background information
The Hamming Code is used to correct errors, so-called bit flips, in data transmissions. Later in the description follows a detailed explanation of how it works. In this Kata we will implement the Hamming Code with bit length 3, this has some advantages and disadvantages:
✓ Compared to other ... |
0f3a0986eca10bd23af88c452f467053d670078e | SevenWen/OSCP | /AllHex.py | 124 | 3.515625 | 4 | # !/usr/bin/python
hex=0x00
f=open("Allhex","w")
while(hex<=0xff):
f.write("\\x"+format(hex, '02x'))
hex+=1;
f.close()
|
5ab6c31ba152486e5a688db77a2496e3257b0cd6 | cloud-cloudbooks/Python_2018 | /Python_2017_summer/Study_Day3/D3_07_for_turtle.py | 115 | 3.609375 | 4 |
import turtle as t
t.shape("turtle")
for i in [1, 2, 3, 4, 5] :
t.forward(100)
t.left(72)
t.done()
|
6deb6991fc53c91c7e710acfbc947cddf56faa5e | jbischof/algo_practice | /epi2/heap_test.py | 514 | 3.5 | 4 | import unittest
import heap
class HeapTest(unittest.TestCase):
def testMergedSortedLists(self):
lists = [[1, 4, 7], [2, 4, 6], [5, 9, 10]]
self.assertEqual(heap.merge_sorted_lists(lists),
[1, 2, 4, 4, 5, 6, 7, 9, 10])
def testContainerWithMedian(self):
a = [1, 0, 3, 5, 2, 0, 1]
... |
22bbf836f90ff2c327c71e69dfd5157e17775ec3 | bhusalashish/DSA-1 | /Data/Binary Search/Peak Element/Maximum element in a Bitonic Array.py | 1,274 | 3.703125 | 4 | '''
#### Name: Maximum element in a Bitonic Array
Link: [youtube](https://www.youtube.com/watch?v=BrrZL1RDMwc&list=PL_z_8CaSLPWeYfhtuKHj-9MpYb6XQJ_f2&index=18)
**Brute**: Use linear search to get the answer in O(n)
Finding peak element (But bitonic array will have single peak element)
'''
def max_elem(arr)... |
5bf8d3a6c7f5e102e6ec5f95ab138ea48d82ec3d | abhinavashok/practice-lang | /python/b1.py | 298 | 4.5 | 4 | # Learning Arrays
##Declare an array
a=[3,4,5,6]
#Iterate over the array using for loop
for item in a:
print(item)
# Print using indices
print("a[3]=",a[3])
# using negative indices,when we put negative indice it goes to 0-(indice) meaning the other side of the array.
print("item=",a[-1])
|
e6a0395d36420031180227839b80062b8703b777 | martinmeagher/UCD_Exercises | /Module9_Intermediate_Data_Visualization_with_Seaborn/1c_Regression_Plots_in_Seaborn.py | 646 | 3.953125 | 4 | # Create a regression plot of premiums vs. insurance_losses
sns.regplot(data=df, x="insurance_losses", y="premiums")
# Display the plot
plt.show()
# Create an lmplot of premiums vs. insurance_losses
sns.lmplot(data=df, x="insurance_losses", y="premiums")
# Display the second plot
plt.show()
# Create a regression p... |
ff5e4962b1330f5f7e606687ebf489bf3323a5f2 | LuciferCoder/Python_Learn_2019 | /day2/demo05.py | 1,639 | 4.09375 | 4 | """
关系运算符:
== != > < >= <=
左边 运算符 右边 --> bool True False
== : 比较的是内容, 返回值是True| False
is:比较的是地址, 可以通过id(变量)获取地址
逻辑运算符:
"""
a1 = 9
a2 = 9
print(a1 < a2)
print(a1 > a2)
print(a1 == a2) # 恒等于的判断 True
print(a1 != a2) # False
b1 = 10000
b2 = 10000
print(b1 == b2) # 比较的是内容
print(b1 is b2) # 比较的是... |
17d82dc51c8bda8bfa4ae1da614b35d6eae9b63b | Liav8/Games.cards | /DeckOfCards.py | 876 | 3.6875 | 4 | from Card import *
from random import *
# מחלקה שיוצרת חבילת קלפים מסודרת (52)
class DeckOfCards:
def __init__(self):
self.cards = cards = []
names = {1: "Diamond", 2: "Spade", 3: "Heart", 4: "Club"}
for number in range(1, 14):
for suit in names.values():
cards.... |
ab3f7c15d89d3a19dd09d222974b40681419425a | m-ox/python_course | /homework/4-19-21_wallet.py | 4,713 | 3.96875 | 4 | """
- Must include 1 class
- Must have some sort of main menu and accept user input to route logic flow
- Needs to have the following functionality:
- Check Balance
- Deposit
- Withdrawal
- Exit
- Must manage balance accurately (balance should reflect transactions).
"""
class Wallet():
def squiggly(self... |
67b133fa7d41ff1d4add2d75652d03044f9e7b8d | jungwonkkim/swexpert | /boj14624.py | 257 | 3.671875 | 4 | cmd = int(input())
if cmd%2:
string = '*' * cmd + '\n'
string +=' '*(cmd//2) + '*' + '\n'
for i in range(1, cmd//2+1):
string += ' ' * (cmd//2-i) + '*' + ' '*(2*i-1) + '*' + '\n'
print(string)
else:
print('I LOVE CBNU') |
c78637914601bccf2ec3a5f1d0c47020e78b5c2e | richasharma3101/-100--Days-of-Code | /code/Day-5/cp.py | 272 | 3.90625 | 4 | def compound_interest(P,R,T):
CI = P * (pow((1 + R / 100), T))
print("Compound interest is", CI)
P=float(input("Enter the value of principle"))
R=float(input("Enter the value of rate"))
T=float(input("Enter the value of time"))
compound_interest(P,R,T)
|
359d00700518521574c8305121781ca4c9aea4db | mateusziwaniak/Python-course-M.Dowson-book---tutorial | /Rozdzial 5/zadanie rozdzial5.py | 1,149 | 3.96875 | 4 | scores = []
choice = None
while choice != "0":
print(
"""
Najlepsze wyniki
0 - zakończ
1 - pokaż wyniki
2 - dodaj wynik
3 - usuń wynik
4 - posortuj wyniki
"""
)
choice = input("Twoj wybor to: ")
if choice == "1":
... |
e6976c940de948634f7ebb4a4913e0ddee6948b9 | ChenxiiCheng/Python-LC-Solution | /Q3-Longest Substring Without Repeating Characters-Medium.py | 1,298 | 3.8125 | 4 | '''
Question:
3. Longest Substring Without Repeating Characters
Descrition:
Given a string, find the length of the longest substring without repeating characters.
Examples:
1.Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
2.Input: "bbbbb"
Output: 1
Expl... |
f7b7940bdc1c2e30f4e81b41256c5bde20674910 | capeman1/Lessons_for_egor | /example_OOP.py | 3,111 | 3.84375 | 4 | class biological_class:
def __init__ (self, name, height, weight , age, gender ,organism=bool):
self.name = name
self.height = height
self.weight = weight
self.age = age
self.gender = gender
self.organism = organism
from rando... |
7aebaed21d42448c0a66866247916ffe3c0371bc | JJ-Woods/Euler | /Python/pe009.py | 628 | 3.53125 | 4 | #Author - Jamie Woods
#https://projecteuler.net/problem=9
import math
TARGET = 1000
def main():
answer = findProductOfTriplet()
print("The solution to problem 9 is " + str(answer))
def findProductOfTriplet():
for a in range(1, TARGET):
for b in range(1, TARGET):
aSquared = a ** 2
... |
67795d31809deb054cdc2e520ed8c5805beca481 | Alekceyka-1/algopro21 | /part1/LabRab/labrab-02/02.py | 163 | 3.625 | 4 | def get_count_div(num):
count = 0
for i in range(2, num):
if num % i == 0:
count += 1
return count
n = 12
print(get_count_div(n))
|
c45623b4662563adeb72e52f2386f83f0d0b2691 | KFranciszek/pylove-training | /1.1/Excersise_1_7.py | 264 | 3.5625 | 4 | def odwazniki(a,b):
ab = a * b
aa = a
bb = b
while bb != 0 :
cc = bb
bb = aa % bb
aa = cc
ab = ab / aa
return (int(ab/a),int(ab/b))
print(odwazniki(2, 8))
# 4, 1
print(odwazniki(4, 6))
# 3, 2
print(odwazniki(6, 4)) |
fb34eb8ca6b3892e237f63aef15af77c3e834c25 | hoyasmh/PS | /boj/02001-03000/2083.py | 123 | 3.796875 | 4 | s=input().split()
while s[0]!='#':
print(s[0],['Junior','Senior'][int(s[1])>17 or int(s[2])>79])
s=input().split()
|
f3e9ffa43dec8739a25bacf9c97f2c13b5dcc46b | whuybrec/MiniGamesBot | /minigames/blackjack.py | 4,068 | 3.765625 | 4 | import random
# https://gist.github.com/getmehire/013c6157eb0ddb26eb7a3965b5f58ae4
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {
'Two': 2,
'Three': 3,
'Four': 4,
'Five': 5,
... |
239648424bcfe928a1e543e0d51583e23c6434e2 | mshukuno/Library-Utilities | /test/true-locations.py | 5,638 | 4.0625 | 4 | """Make a list of locations of true values in a boolean 2-D array.
Usage:
python {this-script} [ {input-file} ]
This script reads a text file with the data for a 2-dimensional boolean array.
The format of the file is the one used by the Read2DimArray method in the
Bool class of the Landis utility library (Landis.... |
ad9b97e96133ed28b9014ab0d7fcf8cb679430f9 | MDGSF/JustCoding | /python-leetcode/sw_58_2.py | 365 | 3.59375 | 4 | class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
n = n % len(s)
a = list(s)
self.reverse(a, 0, n - 1)
self.reverse(a, n, len(a) - 1)
self.reverse(a, 0, len(a) - 1)
return ''.join(a)
def reverse(self, a, left, right):
while left < right:
a[left], a[right] = a[righ... |
15c090827cf86829b4e735f26cd22e4a1a5b2a6e | xjwhhh/TensorflowTutorial | /LearnAndUseML/TextClassification.py | 5,314 | 3.5625 | 4 | # 电影评论分类
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
# Download the IMDB dataset
imdb = keras.datasets.imdb
# 训练集,测试集
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
# Explore the data 数据全部是数字
p... |
158d6d323cfdb15fbe1bcce604de96900a642e12 | Python-Repository-Hub/Learn-Online-Learning | /Python-for-everyone/02_Data_Structure/10_Tuple/03_adventage.py | 357 | 3.984375 | 4 | (x, y) = (4, 'fred')
print(y) # fred
(a, b) = (99, 98)
print(a) # 99
def t() :
return (10, 20)
x, y = t()
print(x, y) # 10 20
# () is recognized as a tuple, even if it is not used.
x, y = 1, 10
print(x, y) # 1 10
x, y = y, x
pr... |
429ab48b9cf07f2b51ee9eb9493991c66bfc5b91 | jorgemira/codewars | /katas/5kyu/kata8.py | 296 | 3.609375 | 4 | """
Codewars 5 kyu kata: Multiples By Permutations II
URL: https://www.codewars.com/kata/5ba178be875de960a6000187/python
"""
def find_lowest_int(k):
n = 1
while True:
if sorted(str(k * n)) == sorted(str((k + 1) * n)):
return n
else:
n += 1
|
dd7b263d4fee276498e0b7954e1fe82e8c0410aa | ariayukin/python_study | /fishc No6.py | 2,011 | 3.96875 | 4 | -3 ** 2
3 ** -2
#and not or
not True
not 0
not 1
3 < 4 < 5
#优先级 幂运算 < 正负号 < 算术操作符 < 比较操作符 < 罗技运算符
#测试题:
#0. Python 的 floor 除法现在使用 “//” 实现,那 3.0 // 2.0 您目测会显示什么内容呢?
#1.0
#1. a < b < c 事实上是等于?
#(a < b) and (b < c)
#2. 不使用 IDLE,你可以轻松说出 5 ** -2 的值吗?
#0.04
#幂运算操作符比其左侧的一元操作符优先级高,比其右侧的一元操作符优... |
5d75d6468c05a33c83854693fd1199bb83cb02ac | joeday05/Problem-Sets | /iterative vs recursive.py | 1,402 | 3.90625 | 4 | def iterMul(a, b):
result = 0
while b > 0:
result += a
b -= 1
return result
def iterPower(base, exp):
result = 1
while exp > 0:
result *= base
exp -= 1
return result
#print iterPower(10 , 2)
def recurMul(a, b):
if b == 1:
return a
else:
... |
7397a369153e6d9b76c51a09beaf084d902e9613 | Jordonguy/PythonTests | /UsefulPythonCodeLibrary/CountEven.py | 345 | 4.28125 | 4 | count_even = 0
count_odd = 0
# Range to 101 because it doesn't include 101 it will only include upto 100
for number in range(1, 101):
if number % 2 == 0:
count_even += 1
print(number)
else:
count_odd += 1
print(number)
print(f"We have {count_even} even numbers")
print(f"We have {... |
03c83c53be652d41555d16c18e130fbcb12fe60d | Anvi23/Practice_Programs | /SummaryProgram.py | 1,545 | 3.578125 | 4 | filep = open('StudentsData.csv','r')
gender = {}
college = {}
cat = {}
for line in filep:
data = line.strip().split(',',3) #creating individual list and not saving the list just checking for values.
'''
[0] -> Name
[1] -> Category
[2] -> Gender
[3] -> College
'''
if data[3] in college... |
9ffa71ae802ba63c06f0a3de7fe208db25af2ae5 | LavanyaJayaprakash7232/python-code---string | /up_low.py | 555 | 4.3125 | 4 | '''
Get a string
Return number of lowercase and uppercase characters
'''
#Function to count the characters
def up_low(string):
up = 0
low = 0
string1 = string.replace(' ', '') #To remove the whitespaces
for i in string1:
if i==i.upper():
up = up + 1
elif i==i.lowe... |
36aef5cd24f30dbf6d9256384945f417ee67abe8 | jmgc/pyston | /test/tests/descriptor_ics.py | 621 | 3.546875 | 4 | # Make sure that we guard in a getattr IC to make sure that
# we don't subsequently get an object with a __get__ defined.
class D(object):
def __repr__(self):
return "<D>"
class C(object):
def __repr__(self):
return "<C>"
d = D()
c = C()
def print_d(c):
print c.d
print_d(c)
def get(... |
417d251240aaf565c206b7c366a6952dd4c1f5fc | bernardombraga/Solucoes-exercicios-cursos-gratuitos | /Curso-em-video-Python3-mundo1/ex025.py | 147 | 3.59375 | 4 | lido = str(input('Qual é seu nome completo? '))
nome = lido.strip().lower()
silva = 'silva' in nome
print('Seu nome tem Silva? {}'.format(silva))
|
65ad5336dbad4a9846cb547ae86f894e4d8e31b3 | xiidot1303/For-study-module- | /1-amaliy topshiriq/3.py | 66 | 3.53125 | 4 | import numpy as np
a = input()
a = int(a)
print(np.sqrt(3*a*a/4)) |
464b4e7c23c619666654f55a41198ab1108cc36d | YRApril/LiJia | /21.04.13/others/GerryChain-main/gerrychain/tree.py | 12,692 | 3.6875 | 4 | import networkx as nx
from networkx.algorithms import tree
from .random import random
from collections import deque, namedtuple
def predecessors(h, root):
return {a: b for a, b in nx.bfs_predecessors(h, root)}
def successors(h, root):
return {a: b for a, b in nx.bfs_successors(h, root)}
def random_spanni... |
a68ea520cbdb94f93ffe4f2ec292966096860462 | taehwan920/Algorithm | /baekjoon/2857_FBI.py | 214 | 3.625 | 4 | FBI = False
FBIs = []
for i in range(1, 6):
agent = input()
if "FBI" in agent:
FBI = True
FBIs.append(i)
if FBI:
for i in FBIs:
print(i, end=" ")
else:
print('HE GOT AWAY!')
|
c8300d2da7059f2cca63417e200e7cc4bbc06183 | RahatIbnRafiq/leetcodeProblems | /Tree/501. Find Mode in Binary Search Tree.py | 632 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
d = None
def dfs(self,node):
if node:
self.d[node.val] = self.d.get(node.val,0)+1
sel... |
88a0516109dcda0a70df265d79a6de264dd56ca3 | NatanLisboa/python | /exercicios-cursoemvideo/Mundo1/ex003.py | 306 | 3.90625 | 4 | # Desafio 003 - Crie um programa que leia dois números e mostre a soma entre eles
print('\033[7;34;40mDesafio 003 - Soma entre dois números\033[m')
n1 = int(input('1º número: '))
n2 = int(input('2º número: '))
print('{} \033[31m+\033[m {} \033[31m=\033[m \033[4;34m{}\033[m'.format(n1, n2, n1+n2))
|
7d70e952732f1d990b807f7681b8c301a87e4ac4 | harshil1903/leetcode | /Design/1603_design_parking_system.py | 1,491 | 4.15625 | 4 |
# 1603. Design Parking System
#
# Source : https://leetcode.com/problems/design-parking-system/
#
# Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each
# size.
#
# Implement the ParkingSystem class:
#
# ParkingSyste... |
33ddf91a2651c35757ddb2cc60ccb4f6317c3f94 | saransappa/My-Codeforces-Solutions | /1281A - Suffix three/1281A.py | 230 | 4.15625 | 4 | n=int(input())
for i in range(n):
s=input()
if s.endswith("po"):
print("FILIPINO")
elif s.endswith("desu") or s.endswith("masu"):
print("JAPANESE")
elif s.endswith("mnida"):
print("KOREAN") |
ba00d6915eb61e95d3a4ffd41f512f38b570ccb1 | 2292527883/Learn-python-3-to-hard-way | /ex25/ex25.py | 1,569 | 4.34375 | 4 | def break_words(stuff): # 作用:将字符串以空格的判断条件分割
"""This fution will break up words for Us ."""
words = stuff.split(' ') # split作用:将stuff的字符串以(' ')之间的字符分割此处为空格
return words
def sort_words(words): # 降序排序
"""sorts the words ."""
return sorted(words) # sorted()作用:将字符串进行降序排序
def print_firs... |
474b15ac2e4314e7ee5df2f2835b2ecd2b2367b5 | poornasandur/DataScienceStanford | /PopulationWikipedia/Lab_2_A_Live.py | 5,715 | 4.25 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import cs109style
cs109style.customize_mpl()
cs109style.customize_css()
# special IPython command to prepare the notebook for matplotlib
%matplotlib inline
from collections import defaultdict
import pandas as pd
import matplotlib.pyplot as plt
import... |
4a11c643ca1ddccaffd3dc4560bd3bb0b1d885a2 | robotech412/ITESCAM-ISC | /Segundo-Semestre/Algebra Lineal/Operaciones con matrices/operaciones_matrices.py | 6,656 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as ny
import sys
def suma ():
print ("SUMA DE MATRICES \t")
filas = int(input("inserte numero de filas: "))
columnas = int(input("inserte numero de columnas: "))
A = [[0 for x in range(filas)] for y in range(columnas)]
print ("Matriz 1")
... |
187a193805b80d95d1b77548a4e70f07f947a66e | Siyaoma812/Coursera-Data-Science-Courses | /Coursera_Course 2 Using Python to Access Web Data /Chapter 12 Networks and Sockets/assignment 2 Scraping Numbers from HTML using BeautifulSoup.py | 719 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 11 22:46:02 2018
@author: Sylvia
"""
#Scraping Numbers from HTML using BeautifulSoup In this assignment
#you will write a Python program similar to http://www.py4e.com/code3/urllink2.py.
#The program will use urllib to read the HTML from the data ... |
aa5c112146bdb7ff88907d1c31d7d29b07a6755e | rosettaplus007/Anagrams.github.io | /visualize/src/js/python.py | 526 | 3.546875 | 4 | import urllib.request
from collections import defaultdict
words = urllib.request.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split()
anagram = defaultdict(list) # map sorted chars to anagrams
for word in words:
anagram[tuple(sorted(word))].append( word )
count = len(anagram[0])
for ana in a... |
adf34a0a97a911fb9ece21ccbce044cbd442be46 | Neo-Teyrall/Mydock | /Langage/Python/Class/addition.py | 745 | 3.765625 | 4 | import sys
import traceback
class addition():
def __init__(self, new_x, new_y):
self.x = new_x
self.y = new_y
pass
def __add__(self,add):
if not isinstance(add, addition) :
traceback.print_stack()
sys.exit("Error: is not addditon class. Addition Impossi... |
b009e6a7cc2b0677d189606ea3af1d9bf31b8169 | Abdulrahman-Adel/Data-structures-and-Algorithms-Udacity-ND | /Problems vs. Algorithms/Problem 2.py | 2,148 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 16:32:59 2020
@author: Abdelrahman
"""
def findPivot(arr, low, high):
if high < low:
return -1
if high == low:
return low
mid = (low + high) // 2
if mid < high and arr[mid] > arr[mid + 1]:
... |
731eb6bbc2c2c1f517a6a9f4e27f0f2e3b1b7b55 | bebarrentine/AnytimeWeightedAStar | /a_star/breadth_first_search.py | 1,862 | 3.625 | 4 | from collections import deque
from node import Node
def breadth_first_search(problem=None):
state_space = {}
expanded = 0
queue = deque([Node(
state=problem.initial_state,
path_cost=0,
parent=None
)])
queue[0].in_frontier = True
generated = 1
while queue:
... |
b2e3fa73a96045b226188e7c7011bd631b016793 | adolfonovoa/nyd | /tres.py | 436 | 3.828125 | 4 | # -*- coding: utf8 -*-
cant1= input('Digite la cantidad invertida de la primera persona')
cant2= input('Digite la cantidad invertida de la segunda persona')
cant3= input('Digite la cantidad invertida de la tercera persona')
float(cant1)
float(cant2)
float(cant3)
suma=cant1 + cant2 + cant3+ 0.0
porc1=(cant1/suma)*100
p... |
c060f1b810089ce5de44ae978462260f3c43d488 | janiszewskibartlomiej/Python-Postgraduate_studies_on_WSB | /10_2019/Part1_ex_GR2.py | 5,409 | 3.5625 | 4 | # -*- coding: utf-8 -*-
####################
# PART 1 exercises #
####################
#--- Exercise 1 -----
# a) Utwórz zmienną x i przypisz do niej wartość 3.
# b) Utwórz zmienną y i przypisz do niej wartość 4.0.
# c) Dodaj obie liczby. Jaki wynik otrzymasz? Jaki jest typ zmiennej wynikowej?
x = 3
y = 4.0
z = ... |
cc93e4274b39484bc9d7cf269b7d024405314eea | Aaron-Raphael/Problems-vs-Algorithms | /4_Problem.py | 2,606 | 4.15625 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
traversal_ind = 0
lower_ind = 0
upper_ind = len(input_list) - 1
while traversal_ind <= upper_ind:
... |
eb038c9f995a1d1561a6ebfc19a504a393ac4b5f | dankodak/Programmierkurs | /Abgaben/Blatt 6/Aufgabe 2/Team 48628/Thich_David_DavidThich_1761477/Aufgabe_6.2_b.py | 718 | 3.765625 | 4 | import time
import numpy as np
def time_it(func, m = 10):
tstart = time.clock()
for i in range(m):
func()
return (time.clock() - tstart) / m
def numpy(A = np.ones((100,100))):
C = np.dot(A, A)
return C
def matrix_multiplication(A = np.ones((100,100))):
[I, J] = A.shape
C = np.zeros(... |
6c1c0fa6dc2a2f5a938cc06a87e5084a7138b111 | Alex2Pena/data-structures-and-algorithms | /Python/code_challenges/array_reverse/array_reverse.py | 185 | 3.609375 | 4 | # res = arr[::-1] #reversing using list slicing
# arr.reverse() #reversing using reverse()
# result=list(reversed(arr))
# new_arr.reverse()
# res_arr=array.array('i',reversed(new_arr))
|
02ab7a2647e2e95688519bdf9d89f1b07f0178fe | huhudaya/leetcode- | /剑指offer/面试题05. 替换空格.py | 839 | 3.625 | 4 | '''
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
'''
class Solution:
def replaceSpace(self, s: str) -> str:
s1 = [] # 设列表
for cha in s: ... |
71ce09395cfda02e35b0ea771874829d05c3e7d6 | DivinGu0721/python | /2.7/test.py | 449 | 3.828125 | 4 | # -*- coding: UTF-8 -*-
list = ['divin','teddy',01234,'abcde',666]
minilist = ['abc',123 ]
print list
print minilist
print "['"+ list[1]+"']"
print list[1]
print list[0:2]
tinydict = {'name': 'john','code':6734, 'dept': 'sales','yes':'oh','no':'haha'}
print tinydict.keys()
print tinydict.values()
print tinydict['yes... |
9510f0c8bea151b6b1d666bb85a3ccf0fa01ed4a | nicholask98/Hangman | /main.py | 3,694 | 3.96875 | 4 | import random
from os import system, name
# import sleep to show output for some time period
from time import sleep
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
word_list = ['de... |
7ce279f9b01b2168826b3280dd27bc62d483eaea | bingli8802/leetcode | /0017_Letter_Combinations_of_a_Phone_Number.py | 922 | 3.515625 | 4 | class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
'''
2 3
/|\
a b c
/|\
d e f
'''
def backTrack(i, tmp):
if i == n:
output.append(tmp)
... |
ee3fbaa4b872c3d578464b8cce2cdc7b67e024f6 | snaga/aind | /Lesson 03 Solving a Sudoku with AI/function.py | 5,715 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import sys
from utils import *
def eliminate_one(values, unit_keys, target):
for k in unit_keys:
if len(values[k]) == 1:
# print("%s = %s" % (k, values[k]))
target = target.replace(values[k], "")
return target
def get_rows_cols(k):
if k[0] in 'ABC':... |
170e29d5b02b5c7135e284f58186108193cfaaa0 | rehmanm/deep-learning | /assignments/assignment1/question4.py | 228 | 3.921875 | 4 | text = input("enter text:")
listText = list(text)
dictText = {}
for str in listText:
currentValue = dictText.get(str, 0)
dictText[str] = currentValue + 1
for key, value in dictText.items():
print(key, ',', value) |
6e8c2370967bd42d5eaae48d40c3052cf4403eec | Nooder/Cracking-Codes-With-Python | /Chapter 9 - PROGRAMMING A PROGRAM TO TEST YOUR PROGRAM/TranspositionEncrypt.py | 1,205 | 4.21875 | 4 | #! python3
# Chapter 7 Project - Transposition Cipher Encryption
def main():
plaintext = "Common sense is not so common."
key = 8
cipherText = encryptMessage(key, plaintext)
print(cipherText)
def encryptMessage(key, message):
# Each string in ciphertext represents a column in t... |
fe1c85aa8ee9f886561114598242a0f26c9e26d9 | FeHeap/PythonPractice | /PyGamePractice/ObjectEncapsulation.py | 1,256 | 3.53125 | 4 | # -*- coding = utf-8 -*-
# @Time: 2021/7/15 下午 05:21
# @Software: PyCharm
import pygame
import sys
pygame.init()
size = width , height = (400,600)
pygame.display.set_caption("draw image")
screen = pygame.display.set_mode(size)
#設置圖像的幀數率
FPS = 60
clock = pygame.time.Clock()
#定義玩家的類
class Player:
def __init__(s... |
7fb24e6ccf89e75e16a642dd6758cd21dda204ad | akshaynagpal/python_snippets | /code snippets/remove_duplicates.py | 531 | 3.984375 | 4 | #function remove_duplicates takes in a list and removes elements of the list that are the same.
def remove_duplicates(input_list):
result = []
k = -1
for i in input_list:
k += 1
flag = False
for j in range(0,k,+1):
if(input_list[j] == i):
flag = True
... |
bb1b20a1fed7dfb75acae0324e2caf914d323c4a | manjuprasadshettyn/pythonprogramming | /ChineseZodiac.py | 612 | 4.15625 | 4 | # Chinese Zodiac sign is based on 12 year cycle and each year is represented by an animal.
year= eval(input("Enter your birth year "))
sign=year%12
print("your Chinese Zodiac Sign is ")
if sign==0 :
print("Sheep")
elif sign == 1 :
print("Monkey")
elif sign == 2 :
print("Roaster")
elif sign == 3 :
print("Dog")
e... |
de8d4a940fb3c2098f2e4b6ff689f5a1a69e749f | mushamajay/PythonAssignments | /question8.py | 345 | 4.21875 | 4 | def maximum(numOne, numTwo):
if numOne>numTwo:
return numOne;
else:
return numTwo;
numOne = float(input("Enter your first number: "))
numTwo = float(input("Enter your second number: "))
print("You entered: {} {} " .format(numOne,numTwo))
print("The larger of the two numbers is: {} " .format(... |
b806dd276b51f3552e9eeb6e100f2e34fda85854 | soheil2017/Machine-Learning | /MatPlotlib/barchart.py | 2,288 | 3.875 | 4 | #https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py
"""
=============================
Grouped bar chart with labels
=============================
Bar charts are useful for visualizing counts, or summary statistics
with error bars. This example ... |
89ba46d2ee7e5440ba54813b65a118487c218f05 | chenfengrugao/pythontutorial | /day3/string_slice.py | 402 | 3.984375 | 4 | #!/usr/bin/python3
# slice
# 1.
a = 'hello world'
b = a[0]
c = a[10]
print(b, c) # h d
# 2.
b = a[-1]
c = a[-2]
d = a[-3]
print(b, c, d) # d l r
# 3.
b = a[0:3]
c = a[1:3]
print(b, c) # hel el
# 4.
b = a[:2]
c = a[1:]
d = a[:]
print(b) # he
print(c) # ello world
print(d) # hello world
... |
7e582d3dd0f5fe807a4d92bc61f17000e49f725c | jdiaz-dev/practicing-python | /SECTION 0 more about python/python/15 Truthiness.py | 1,327 | 4.28125 | 4 | #Python uses the value None to indicate a nonexistent value. It is similar to other languages’ null:
x = None
assert x == None, "this is the not the Pythonic way to check for None"
assert x is None, "this is the Pythonic way to check for None"
"""
* all these values is threaded as False by Python
- False
... |
1ed8baf3d400de35afa42694bc798b6442405d84 | bluella/hackerrank-solutions-explained | /src/Greedy Algorithms/Luck Balance.py | 1,891 | 4.0625 | 4 | #!/usr/bin/env python3
"""
https://www.hackerrank.com/challenges/luck-balance
Lena is preparing for an important coding competition
that is preceded by a number of sequential preliminary contests.
Initially, her luck balance is 0. She believes in "saving luck", and wants to check her theory.
Each contest is described b... |
d5da64d898cd3e1b27727e6bc7cf4a4eb37e6900 | EdwaRen/Competitve-Programming | /Leetcode/202.happy-number.py | 832 | 3.75 | 4 | class Solution(object):
def isHappy(self, n):
# Calculate next num based off sum of squares of digits
def next(num):
happy = 0
while num > 0:
digit = num % 10
happy += digit * digit
num = int(num/10)
return ... |
b1d4d0e8f69c05d6f91bf0b264720001750aa7ed | manojakumarpanda/This-is-first | /pattern/pyramid pattern.py | 1,148 | 3.953125 | 4 | #program for the reverse pyrmaid pattern for the alphabets
'''for the four row patterns
A B C D
A B C
A B
A '''
row=int(input('Enter the number of row you want to print::'))
for i in range(row):
print(' '*i,end=' ')
for j in range(row-i):
print(chr(65+j),end=' ')
print()
#programs f... |
d5b9d59ab6d0bdde9338bb39ead0e64c9ce77bc0 | quanysq/study | /Python/MachineLearning/chapter24/scatter.py | 716 | 3.734375 | 4 | # 散点图显示成对数据集的可视化关系是比较好的
from matplotlib import pyplot as plt
friends = [70,65,72,63,71,64,60,64,67]
minutes = [175,170,205,120,220,130,105,145,190]
labels = ['a','b','c','d','e','f','g','h','i']
plt.scatter(friends, minutes)
#每个点加标记
for label, friend_count, minute_count in zip(labels, friends, minutes):
plt.anno... |
4e58b05699e8aabc60edc837ff3075113e3aa50e | GalCohen/GetStartedSnippets | /Python/lambda.py | 320 | 3.84375 | 4 |
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages)
squares = range(1, 11)
squares = [x**2 for x in range(1,11) if (x**2 == x**2)]
print squares
print filter(lambda x: x > 30 and x < 70, squares) |
7d2d4af8df9f967f4bf85ae363eea1d0f6c1d3c9 | godwinreigh/web-dev-things | /programming projects/python projects/experiment/testing.py | 95 | 3.671875 | 4 |
for n in range(10):
print(n % 2)
def my_func(n1, n2):
return n1 + n2
my_func(1,2,3) |
d2d8698c1a761dbde50bd05a2b8c7736e892edae | AmitBaanerjee/Data-Structures-Algo-Practise | /leetcode problems/994.py | 1,827 | 3.5625 | 4 | 994. Rotting Oranges
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the mini... |
1ccece800a90aa2bf90d39f04d01849ac42d1525 | mubaarik/digitalCommunications | /PS1_audiocom/PS1.py | 6,769 | 3.765625 | 4 | import heapq
import operator
import sys
from collections import defaultdict
class HuffmanTree:
# Huffman Trees always have a probability. For internal nodes,
# symbol will be None, and left and right children will be
# defined. For leaf nodes, symbol will *not* be None, but the
# children will be.
... |
b98ef0c1c6521511be2a762d914cd99994abe783 | bdabrowski/simple-calculator | /operators.py | 1,674 | 4.0625 | 4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Add operators here
class Operator(object):
"""
Interface for operators.
Operator must be only one char long.
"""
sign = None
def __init__(self):
if not self.sign:
raise Exception('Operator sign is missing.... |
21e9cf1d19e7e6d0be9ebc60688a6550908e7779 | linuxmahara/generative_art-1 | /ball_animations/ball_collisions/02_colliding.py | 1,497 | 3.671875 | 4 | """
This is one script in a series.
In 01.. we have the ability to launch a set of balls inside a confined Box
Note: This requires that the file ball.py (rename 01ball.py to ball.py) to be in the same folder
Author: Ram Narasimhan
August 2020
"""
from ball import Ball
import colors
w, h = 600, 600
radius = 10
nu... |
112f44cb5083c63580ec76da625f1e21abf73a33 | antdevelopment1/python104 | /guess_the_number_play_again.py | 1,190 | 4.03125 | 4 | import random
random_num = 5 #random.randint(1, 10)
print("I am thinking of a number between 1 and 10. ")
user_input = int(input("Please guess a number? "))
correct_guess = False
limit_guess = 3
while correct_guess == False:
if user_input == random_num:
print("Yay you won!!!")
ask_to_play ... |
dbb91480afda7a8677176783a4f109732bd01f64 | t734070824/tq.python | /tq.python/study/_web/1_basic/if_else.py | 396 | 4.25 | 4 | age=14
if age >= 18:
print("your age is : ", age)
print("adult")
else:
print("gag")
print("teenager")
age=4
age=4
if age >= 18:
print("your age is : ", age)
print("adult")
elif age > 6:
print("gag")
print("teenager")
else:
print("123")
print("--------------")
birth = input("birth:... |
8116a960cad6118f63bd882d01d40d55cdffea7d | Shasaravana/programs | /lenofarr.py | 153 | 3.828125 | 4 | #Length of the array
def lenofarr(arr):
count=0
for _ in arr:
count+=1
return count
arr=[1,2,3,4,5,6]
print(lenofarr(arr))
|
8d3c3d87ce24f3db07732f0c357078b6b6e84853 | tartofour/python-IESN-1BQ2-TIR | /projet.py | 21,672 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# TODO:
#
# - Règles du jeu
# - Change keybind
import random
import datetime
class Menu:
separation_template = ("------------------------------------------------")
def __init__(self, score_file="data.txt", game=None):
self._score_file = score_file
self._game = ga... |
749d348c13e4178941cd30f69d2f1d1c35886b04 | pmosko/JetBrains-Academy | /Password Hacker/stage2.py | 928 | 3.5 | 4 | import argparse
import socket
from string import ascii_lowercase, digits
from itertools import combinations_with_replacement
def connect(args):
with socket.socket() as sock:
sock.connect((args.hostname, args.port))
for length in range(1, 30):
for letters in combinations_with_... |
768b5e12f909d9712cdba3c9c15813ac56f95a66 | MauGarrido/hyperblog | /codigo Python/funciones.py | 476 | 3.921875 | 4 | #def func():
#print ("ola ke ase?")
#func()
#func()
def conversacion (mensaje):
print ("Hola")
print ("¿Cómo estás?")
print (mensaje)
opcion = int(input("Elige una opción (1, 2, 3) "))
if opcion == 1 :
conversacion ("Elegiste la opción 1")
elif opcion == 2:
conversaci... |
3f95aadd808720f3beb7519263bcc7400db0adb2 | mlinkon/ml101 | /VisualaizeDecisionTree/VisualizeIrisFlowerDataSet.py | 2,185 | 3.640625 | 4 | #Iris Flower DataSet [Wikipedia link : https://en.wikipedia.org/wiki/Iris_flower_data_set ]
import numpy as np
import graphviz
from sklearn import tree
from sklearn.datasets import load_iris
iris = load_iris()
print(iris.feature_names) #prints list of features in dataset
print(iris.target_names) #prints all distinct ... |
368f7bcfb356ce071570e6242938b173df5d79ca | Aniket121397/Python | /Python/loops and even odd func/count_EVEN_ODD.py | 196 | 3.875 | 4 | A=[23,54,22,98,45,65,37,31,82,64]
even=0
odd=0
for x in A:
if x%2==0:
even +=1
else:
odd +=1
print("There are:",even,"even numbers")
print("There are:",odd,"odd numbers")
|
08271853fed13e9073f51705e17ee74003c9f0af | frnhsn/2048 | /2048.py | 4,000 | 3.765625 | 4 | # At the moment, this code contain games logic only. This basically just an
# excersie for me in building an algortihm and practicing OOP. I'll create GUI
# version for further development
# For playing the games you could create an object which inherited games() class
# e.g
# play = games()
# play.up()
i... |
b8f99521d38cc11e72da72d45d675b7c49d9abde | C109156212/python | /18.py | 1,690 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 13 19:09:25 2021
@author: 123
"""
a = int(input("測試的資料量"))
for i in range (0,a):
x = input("輸入血型").split(" ")
if x[0]=="O" and x[1]=="O" and x[2]=="O":
print("YES")
elif x[0]=="O" and x[1]=="A" and (x[2]=="O" or x[2]=="A"):
print("YES")
e... |
898719d642f4caad3b8e8ae42adf1bfcc9b7334a | pk111297/PythonDataStructures | /ds/Stack.py | 424 | 3.75 | 4 | class Stack:
def __init__(self):
self.lst=[]
def push(self,num):
self.lst.insert(0,num)
def pop(self):
if len(self.lst)==0:
return "Stack is Empty"
z=self.lst[0]
del self.lst[0]
return z
def isEmpty(self):
if len(self.lst... |
f6d253a1f4f8ab70f72be488d5d8ebe9f1ba5fd4 | RuzhaK/pythonProject | /Fundamentals/DictionariesExercise/T10SoftUniExamResults.py | 459 | 3.59375 | 4 | data=input()
# submissions={}
results={}
while data!="exam finished":
line=data.split("-")
username=line[0]
language=line[1]
if language!="banned":
if username not in results:
results[username] = {"subkey": []}
results[username] = username
if language not in result... |
363e341e47561b71b2f66ae86b82b1515841db5c | naye0ng/Algorithm | /SWExpertAcademy/모의SW역량테스트/1952_수영장.py | 632 | 3.609375 | 4 | """
수영장
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PpFQaAQMDFAUq&categoryId=AV5PpFQaAQMDFAUq&categoryType=CODE
"""
def DFS(m, cost) :
if m >= 12 :
global low_cost
low_cost = min(low_cost, cost)
else :
# 하루
DFS(m+1, cost+cnt[m]*day)
# 한... |
05db84ab52eef47f63d318a873aef6e0f7a6a8a5 | faye-a/Data-Structures-Algorithms-Assignments | /average_runtime.py | 264 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
def calculate_average(array):
#total score
total = 0
for number in range(len(array)):
total += array[number]
#calculate average of total
average = total / len(array)
return average
|
f1fd9a00a1c3a43c8569a3aa54975a071357a987 | Ozcry/PythonCEV | /ex/ex108.py | 884 | 3.890625 | 4 | '''Adapte o código do DESAFIO 107, criando uma função adicional chamada moeda() que consiga mostrar os valores como um
valor monetário formatodo.'''
from utilidadesCeV import moeda
print('\033[1;33m-=\033[m' * 20)
n1 = float(input('\033[34mDigite o preço: R$\033[m'))
por = int(input('\033[33mQuantos porcentos deseja au... |
5e2053f1b601788a1ec99cd1681f7dafcade9401 | Lucy-SD-Developer/Encryption-Decryption | /simple_substitution/frequency.py | 1,561 | 4 | 4 | # English letter frequency in order from the highest to lowest frequency
_WORDS = [ 'E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H',
'D', 'L', 'U', 'C', 'M', 'F', 'Y', 'W', 'G', 'P', 'B', 'V', 'K',
'X', 'Q', 'J', 'Z']
# English letter frequency corresponding to the predefined array words
# data are from English letter fr... |
f1efb22ccc58b8d43bc95f78ede91b5d025af77c | chinna777/demo.py | /ExceptionsStart.py | 599 | 3.6875 | 4 | import logging
logging.basicConfig(filename='myfile.log',level=logging.DEBUG)
try:
logging.info("entering the required inputs")
a,b=[int(x) for x in input('enter the two numbers:' ).split()]
f=open("myfile.py","w")
c=a//b
print(c)
f.write('writing %d into myfile'%c)
logging.info("writin... |
f44062e0038d4f1a6edd6c6bf2ae5721b9d3d572 | codeforcauseorg-archive/DSA-Live-Python-Jun-0621 | /lecture-08/stringpool.py | 90 | 3.546875 | 4 | first = "vtvtuyvoyvoytctcgyocifcygcgcvugvgybhbvvyv"
second = "vtvtuyvoyvoytctcgyocifcygcgcvugvgybhbvvyv"
print(first is second)
print(first[2:5] == second[2:5]) |
e2fc55b51c62dd2dbfa6faaa5c0382b75a60cd2c | piyush9194/data_structures_with_python | /data_structures/trees/lowest_common_ancestor_bt.py | 502 | 3.96875 | 4 | """
Find the LCA of Binary Tree.
https://www.youtube.com/watch?v=13m9ZCB8gjw
"""
def lca(root, n1, n2):
if root is None:
return None
if root.data == n1 or root.data == n2:
return root
node_left = lca(root.left, n1, n2)
node_right = lca(root.right, n1, n2)
if node_left is not Non... |
cbb4737796354e82883c62d67cb46fbf5eb45319 | JustinOliver/ATBS | /testie.py | 591 | 3.984375 | 4 | # A dumb program to learn and mess around with command line
while True:
try:
x = int(input('give me an int: '))
except ValueError:
print ('Dont be an idiot')
continue
else:
break
if x < 4:
print ('less than 4')
elif x == 4:
print ("egual 2 4")
else:
print ('thats a big number')
print("you... |
108234c47694f40b88818654b0102b1b5a8ae04d | Jiklopo/web-dev | /lab7-python/level2/293.py | 147 | 3.875 | 4 | def compare(a: int, b: int):
if a == b:
return 0
return a if a > b else b
a = int(input())
b = int(input())
print(compare(a, b))
|
328f126a4c1e42ddcb6af61b1cca3c0ebbf97965 | gcpdeepesh/harshis-python-code | /What To Wear.py | 549 | 4.21875 | 4 | rainy = input("How`s the weather outside ? Is it raining (y/n):").lower()
cold = input ("Is it cold outside ? (y/n)").lower()
if (rainy == 'y' and cold == 'y'):
print("Is it important, if yes you`d better wear a raincoat otherwise I wil suggest you to stay at home.")
elif (rainy == 'y' and cold == 'n'):
print("... |
48cec89e2f78d2c4464a27c6e26a983aeec58abb | QitaoXu/Lintcode | /Alog/class2/exercises/totalOccurences.py | 1,540 | 3.703125 | 4 | class Solution:
"""
@param A: A an integer array sorted in ascending order
@param target: An integer
@return: An integer
"""
def totalOccurrence(self, A, target):
# write your code here
if not A or target == None:
return 0
start, end = 0... |
5ecc072f66eb13089dedac463551a569da78d6e9 | CauanyRodrigues01/Codigos-Python | /Questões do URI/URI_2344.py | 194 | 3.78125 | 4 | nota = int(input())
if nota == 0:
print("E")
if 1 <= nota <= 35:
print("D")
if 36 <= nota <= 60:
print("C")
if 61 <= nota <= 85:
print("B")
if 86 <= nota <= 100:
print("A")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.