blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b98c86a2342bea83772dac9d620c15e968fb6b97 | xiang-daode/Python3_codes | /T047_变量之互换(变量或元素的位置变动).py | 588 | 3.953125 | 4 | # 在这里写上你的代码 :-)
"""
题目047:变量或元素的位置变动。
"""
def tm047():
# 元组中两个变量值互换
a, b = 1, 2
a, b = b, a
print(a, b)
# 列表中3个变量值互换,顺序倒置
u = [1, 2, 3]
print(u[::-1])
# 元组中5个变量值互换,顺序倒置
v = (1, 2, 3, 4, 5)
print(v[::-1])
# 字典中3个"键-值"对中的值互换
w = {"A": 1, "B": 2, "C": 3}
print(w["C"]... |
73e02d975b50722c0f2d7a94d6d9dda24bec4a71 | Vahid-Esmaeelzadeh/CTCI-Python | /Chapter5/Q5.3.py | 1,074 | 3.546875 | 4 | '''
Flip Bit to Win: You have an integer and you can flip exactly one bit from a O to a 1. Write code to
find the length of the longest sequence of 1s you could create.
EXAMPLE
Input: 1775 (or: 11011101111)
Output: 8
'''
def flipBitToWin(N: int) -> int:
count = 1
newZeroIndex, midZeroIndex, oldZeroIndex = -1... |
1d232ec6c342db5101761d3f40fcd6efa67e429b | diegojserrano/AED | /Guia03/Ej03-05.py | 461 | 3.609375 | 4 | __author__ = 'Catedra de Algoritmos y Estructuras de Datos'
# Titulo y Carga de datos
print('Resumen eleccion centro vecinal')
apellido = input('Ingrese el apellido del candidato: ')
nombre = input('Ingrese el nombre del candidato: ')
votos = int(input('Ingrese la cantidad de votos que obtuvo: '))
# Procesos
... |
380b286fd423c5d364d361e360abbf0653643b13 | dianjiaogit/LeetCode_Python_solution | /Easy/Symmetric_Tree.py | 1,268 | 4.28125 | 4 | # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
# But the following [1,2,2,null,3,null,3] is not:
# 1
# / \
# 2 2
# \ \
# 3 3
# ... |
124c24db007a25bda27be6a335580ec001760c8e | vkjangid/python | /dictionary2.py | 1,361 | 3.828125 | 4 | #common values between two dictionaries
'''d1={'key1':40,'key2':30,'key3':40,'key4':90,'key5':60}
d2={'key1':20,'key2':30,'key3':30,'key4':80,'key5':60}
d3={}
for i in d1:
if d1[i]==d2[i]:
d3.update({i:d1[i]})
print(d3)'''
#adding the value of common keys
'''d1={'key1':40,'key2':30,'key3'... |
00a82f9f204cc09c87cf311e7afae6cd9d975a70 | Guanyi-Wang/leetcode | /424LongestRepeatingCharacterReplacementMedium.py | 1,043 | 3.59375 | 4 | import collections
# slicing window O(N), O(N)
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
if not s:
return 0
if k >= len(s):
return len(s)
longest_len = 0
l = r = 0 # left and right pointers start from beginning, representing a s... |
9524355898228dae7d7ee09b35ab70a71acf95a4 | Kethavath9199/Compilers_Lab_CS341 | /CompilersLab/assignment-2/files/170101024.py | 260 | 3.671875 | 4 | from __future__ import print_function #Only for Python2
with open('file1.txt') as f1, open('file2.txt') as f2, open('outfile.txt', 'w') as outfile:
for line1, line2 in zip(f1, f2):
if line1 == line2:
print(line1, end='', file=outfile)
|
5a9b3d053084303c783801379920eac405b84ae2 | pedrofwanderley/SudokuSolverAI | /samurai.py | 3,251 | 3.546875 | 4 | import grids
import helpers
import elimination
import only_choice
import heuristic
# Merges all the possibiliteis from one intersection of two boards, where
# board_n and board_m: boards whose the blocks in common will be merged
# n_cols and n_rows: the selected cols and rows from board_n
# m_cols and m_rows: the sele... |
162f03edae6ae17006792a533acc87e752e18144 | ALMTC/Logica-de-programacao | /Python/18.py | 97 | 3.6875 | 4 | print 'Temperatura em Fahrenheit'
f=input()
c=(f-32)*(5/9.0)
print str(c) + 'graus ceucios'
|
e77de9ab7cd46fc0e85b7f17d84b65aaf505f69a | techtolearn/Py_Learn | /Cory_Basic/String/ScreteMsg.py | 1,348 | 4.09375 | 4 | '''
https://www.youtube.com/watch?v=-wikR15AYWY&list=PLGLfVvz_LVvTn3cK5e6LjhgGiSeVlIRwt&index=4
prepare the secrete message
'''
message = input('Enter your message : ')
key = int(input('How many character you want to shift (1 - 26) ? '))
secrete_msg = ''
for char in message:
if char.isalpha():
char_code... |
74bc8df624e4e02ab660fa21b4f90a862fcfec9f | daisuke19891023/atcoder_python | /atcoder/abc/142/C/program.py | 512 | 3.78125 | 4 | import sys
input = sys.stdin.readline
import numpy as np
def print_ans(input_line):
"""Test Case
>>> print_ans("2 3 1")
3 1 2
>>> print_ans("1 2 3 4 5")
1 2 3 4 5
>>> print_ans("8 2 7 3 4 5 6 1")
8 2 4 5 6 7 3 1
"""
arr = np.array(list(map(int,input_line.split())))
arr_sort = np.... |
ed787e62183222321dc7348dc2c2256399da336c | lvhanzhi/Python | /python/小练习/金字塔.py | 177 | 3.90625 | 4 | x=int(input("请输入个数:"))
for i in range(1,x+1):
for j in range(1,x-i+1):
print(" ",end='')
for y in range(1,2*i):
print("*",end='')
print() |
25d0607767450f09f4c62f80cfc35ae9dc00ce5f | prabin544/data-structures-and-algorithms | /python/stack_queue_brackets/stack_queue_brackets.py | 1,514 | 3.5 | 4 | openBrackets = ["[", "{", "("]
closedBrackets = ["]", "}", ")"]
def validate_brackets(str):
new_stack = []
for i in str:
if i in openBrackets:
new_stack.append(i)
elif i in closedBrackets:
brackets = closedBrackets.index(i)
if ((len(new_stack) > 0) and (openB... |
84e23b0504147caf1e522ba242ebb5b40d8e87dc | 15cs026priyanka/appu | /factorial.py | 103 | 4.21875 | 4 | num=int(input("enter a number"))
n=1
while num>0:
num=num*1
num=num-1
print("the factorial number is")
|
a9f515244e93dbac1702d594ae3873c30842aedd | AnqiQu27/python_study | /user_profile.py | 248 | 3.546875 | 4 | def build_profile(first, last, **user_info):
''' create a dict to store the info of users '''
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key, value in user_info.items():
profile[key] = value
return profile
|
e85feb33c56dc190b4aca79c8c19710ff73f6169 | 2001Sapsap28/Python-Crash-Course-Book-Tasks | /Do It Yourself section tasks/Chapter 3/3.1.py | 314 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 13:49:19 2020
@author: passmesomesugar~git
"""
# 3-1. Names: Store the names of a few of your friends in a list called names. Print
# each person’s name by accessing each element in the list, one at a time.
names = ["Michael", "Jacob", "Louis XIV"]
print(names)
|
3d8642b2df4cf17946d2a78c7660d52c4b420ac8 | BojPav/FizzBuzz | /FizzBuzz.py | 414 | 3.71875 | 4 | print " ...Welcome to FizzBuzz..."
vnesena_stevilka = int(raw_input("Vnesite stevilo med 1 in 100: "))
print "Vnesena stevilka je: "+str(vnesena_stevilka)
a = 0
for a in range(vnesena_stevilka):
a = a + 1
if a % 3 == 0 and a % 5 == 0:
print "fizzbuzz"
elif a % 3 == 0:
print "fizz"
... |
2e0fe3522cfa52111a48b7ad49abda1e93ce7ee1 | crisgrim/python-katas | /09-kata.py | 380 | 3.84375 | 4 |
def calculate_benefits(capital, percentage, years):
benefit_per_year = (int(capital) * int(percentage)) / 100
return round(benefit_per_year * int(years), 2)
capital = input("Capital to invest: ")
percentage = input("Percentage annual: ")
years = input("Years: ")
profits = calculate_benefits(capital, percent... |
403372c2c7bbeb5b4c024a1732e74aeeb2fad32a | zakidem/DataCamp | /Course/01-Intermediate Python for Data Science/Chapter 1 Matplotlib/Line plot(3).py | 219 | 3.640625 | 4 | # Print the last item of gdp_cap and life_exp
print(gdp_cap,life_exp)
# Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis
x = gdp_cap
y = life_exp
plt.plot(gdp_cap,life_exp)
# Display the plot
plt.show()
|
1d829d3f47abce22bd5c6ec7ab53679b66c54b1c | Ham5terzilla/python | /5th Lesson/ex1.py | 843 | 4.09375 | 4 | # Найдите индексы первого вхождения максимального элемента. Выведите два числа: номер строки и номер столбца,
# в которых стоит наибольший элемент в двумерном массиве. Если таких элементов несколько, то выводится тот,
# у которого меньше номер строки, а если номера строк равны то тот, у которого меньше номер столбца.
f... |
ff62f36213ec3affcfb5596de76d506c84f99ca8 | Shylcok/Python_code_skills | /day2-对象迭代与反迭代技巧/对迭代器做切片操作.py | 528 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# @Project : Python高效编程技巧实战
# @Time : 0223
# @Author : Shylock
# @Email : JYFelt@163.com
# @File : 对迭代器做切片操作.py
# @Software: PyCharm
# ----------------------------------------------------
# import something
# f = open('/var/log/auth.log')
# lines = f.readlines()
# for line in lines:
# ... |
9c81b76210e3ef6f9a1475129e9e1871de94731b | djberenberg/simple-decryption | /decipher.py | 7,910 | 3.859375 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Daniel Berenberg
"""
User facing command line application for deciphering the English simple substitution cipher
This application uses the hill climber algorithm to determine the most likely cipher key
for the provided messages.
One addition to the genetic ap... |
e3b1446253eb02239cceccaafba7260aa39b3c33 | chrismlee26/music-playlist | /Playlist.py | 2,697 | 3.859375 | 4 | from Song import Song
class Playlist:
def __init__(self):
# Set root to None
self.__first_song = None
# The method 'add_song' creates a Song object and adds it to the playlist.
# This method has one parameter called title.
def add_song(self, title):
# This is the HEAD, use a f... |
e8dfb298e14617fb4832dda2d39d9274c37d1b4e | jgerstein/intro-programming-19-20 | /day07/turtleturtle.py | 200 | 3.90625 | 4 | import turtle as t
def circles(sz, reps):
for n in range(reps):
t.circle(sz)
t.rt(360/reps)
if sz > 3:
circles(sz * .8, reps)
t.speed(0)
circles(100, 2)
t.mainloop() |
403822c58c3bbe1f5e04752679d8437f53600f22 | VladOvadiuc/Python | /Family_Expenses/UI_menu_based.py | 3,901 | 3.984375 | 4 | from functions import *
def readCommand():
'''
Read and parse user commands
input: -
output: (command, params) tuple, where:
command is user command
params are parameters
'''
cmd = input("Input option: ")
'''
Separate command word and parameters
'''
if c... |
ede3b050371347d54e73cd6c737a259f7c4d6773 | stretchcloud/Python-Code | /bmi-app.py | 390 | 4.09375 | 4 | def bmi_app():
height = input('How Tall are You? ')
weight = input ('What is your Weight? ')
bmi = int(weight)/(int(height)/100)**2
print('Your BMI is {}'.format(round(bmi,2)))
if bmi < 18.5:
print ('You\'d better eat more')
elif bmi >= 18.5 and bmi <= 24:
print ('Good Job')
... |
a64dec88599f3f55eeeff633e22bd5fb53350267 | AhaanvGithub/Competitive-Programs | /Sets/symmetric-difference.py | 203 | 3.578125 | 4 | # Symmetric Difference
len_a, a, len_b, b = (int(input()),input().split(),int(input()),input().split())
print('\n'.join(sorted((set(b).difference(set(a))).union(set(a).difference(set(b))), key=int)))
|
0f66ebcb04b8d4d19b5ab79a063f57280ff45208 | hiepxanh/C4E4 | /total_digits_and_prime.py | 1,800 | 4 | 4 | from turtle import *
def total_digits(number):
n = number
result = 0
while n != 0:
result += n % 10
n //= 10
return result
# i = 2 -> n - 1
def check_prime(n):
prime = True
for i in range(2, n):
if n % i == 0:
prime = False
return pri... |
361b113e8db4fddadfa45f04520d56427c49cc38 | Frankiee/leetcode | /array/283_move_zeroes.py | 873 | 3.890625 | 4 | # https://leetcode.com/problems/move-zeroes/
# 283. Move Zeroes
# History:
# Facebook
# 1.
# Dec 9, 2019
# 2.
# Apr 13, 2020
# 3.
# Apr 22, 2020
# Given an array nums, write a function to move all 0's to the end of it while maintaining the
# relative order of the non-zero elements.
#
# Example:
#
# Input: [0,1,0,3,12... |
be54b12d47844ada5311c08172c1222c7a84e90c | Rhysoshea/daily_coding_challenges | /leetcode/merge_two_sorted_lists.py | 1,187 | 4.09375 | 4 | """
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Accepted
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None)... |
a00e633f2bedc3a6cdabd6f5d0d65bd23374ff08 | hbradleyiii/nwid | /nwid/terminal/cursor.py | 2,251 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: cursor.py
# author: Harold Bradley III
# email: harold@bradleystudio.net
# created on: 05/30/2017
#
"""
nwid.terminal.cursor
~~~~~~~~~~~~~~~~~~~~
This module contains functions responsible for moving and manipulating the
cu... |
68304a0f1f2cf53220aff2d62642bc2ad5d241e6 | RutujaTikare13/Python-Programs | /chaining.py | 1,335 | 4.125 | 4 | from linkedlist import Linkedlist
hash_table = [None] * 13
class Hashing():
def hash_calculator(self, num):
return num % 13
def insert(self, lst):
for i in lst:
mapping = self.hash_calculator(i)
# print("mapping:", mapping)
if hash_table[mapping] == None:
#print("Creating new linkedlist ", i)
... |
0b8e2ac08c3ae11b5a2c40f3d819b9fbd70179aa | mkoeppel/SPICED_Weekly_Projects | /week_5/bokeh_prophet_mk.py | 5,114 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Step-by-step guide to generating an interactive climate map in Bokeh (& Geopandas)
#
# - **With some specific boilerplate code already filled in.**
#
# - **CREDITS**:
#
# - The idea / code for this lesson was heavily inspired by the following tutorial:
# - [A Com... |
e975b72b9df3ff63ca36181b9f5234e8af9be504 | leclm/CeV-Python | /PythonDesafios/desafio73.py | 1,039 | 3.6875 | 4 | ''' Crie um tupla preenchida com os 20 primeiros colocados da tabela do campeonato brasileiro de futebol, na ordem de
colocação. Depois mostre: a) Apenas os 5 primeiros colocados >> b) Os últimos 4 colocados da tabela >> c) uma lista com
os times em ordem alfabética >> d) Em que posição da tabela está o time da Chape... |
856ade8436be149108576ebb4bfbfc99af574e13 | carmonantonio/python_coursera | /dictionaries.py | 319 | 3.578125 | 4 | # Este programa busca una direccion de correo y guarda la frecuencia en un diccionario
mail = dict()
fh = open('mbox.txt')
for lines in fh:
if not lines.startswith('From: ') : continue
lines = lines.rstrip()
words = lines.split()
for word in words:
mail[word] = mail.get(word,0)+1
print (mail)
|
700ea7bbb319b1390aa379777e6e1c4d01612016 | nlangf2010/python_challenge | /PyBank/main.py | 2,298 | 3.96875 | 4 | import os
import csv
budget_data_csv = os.path.join("Resources", "budget_data.csv")
#create empty lists for data I need to show to live
months = []
profits_losses = []
with open(budget_data_csv) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
# "next" makes sure that the pro... |
1e6537d8ae536a96941dedf553d193f806b55400 | fujihiraryo/aizu-online-judge | /ITP1/11A_Dice1.py | 1,135 | 3.53125 | 4 | class Dice:
def __init__(self, x):
self.top = x[0]
self.front = x[1]
self.right = x[2]
self.left = x[3]
self.back = x[4]
self.bottom = x[5]
def N(self):
self.top, self.front, self.bottom, self.back = (
self.front,
self.bottom,
... |
49729dbedb4e5cb41f09e79c9a5ff461253ae22d | blaketeres/csc521 | /python-quirk/interpreter.py | 13,286 | 3.640625 | 4 | import sys
import pprint
import json
import ast
pp = pprint.PrettyPrinter(depth=6)
def lookupInScopeStack(name, scope):
'''Returns values (including declared functions!) from the scope.
name - A string value holding the name of a bound variable or function.
scope - The scope that holds names to value bind... |
f8c6c8011c97dc1122d6b428e868ca64bebb0127 | ocoetohe/Automation | /Python Crash Course/Chapter 5/5-9_No_Users.py | 205 | 3.515625 | 4 | users = ['barry', 'mariah']
if users:
for user in users:
print(f"\nAdding {user.title()}...")
print(f"Buenos dias {user.title()}!!!\n")
else:
print("We need to find some users!!!") |
23e6399f00712215198bd5d4e5b211d89617774f | mpeschke/PARADIG-PROG-N1-OOP-PYTHON3 | /ooppython3/modalidadearremessopeso.py | 2,228 | 3.65625 | 4 | # coding=UTF-8
"""
Módulo: Fornece classe com todos os métodos necessários para
implementar uma modalidade de competição de Arremesso de Peso.
"""
from ooppython3.modalidade import Modalidade
MENSAGEM_LER_ARREMESSOS = "Entre com os {} arremessos do adversário {}: (Exe" \
"mplo: 9.7,10.0,...):... |
758758ba8b047c586efc358585284d647d9bcbd0 | ConnorJungle/Hockey-Analytics | /track_turnovers.py | 1,900 | 3.625 | 4 | import csv
import numpy as np
def getTurnovers():
''' This program takes a user input to track turnovers and the type of turnover. It will return a CSV file '''
data = [['TEAM', 'PLAYER #', '# TURNOVERS', 'KIND OF TURNOVER']]
InputOK = False
while not InputOK:
TeamOK = False
while... |
69ab849c5786c7da82f25ec6ad89b28c0174a498 | chloenh/Codecademy-Python | /sthofvalue-solution.py | 526 | 4.1875 | 4 | # Task: Create a variable called total and set it to zero.
#Loop through the prices dictionary.
#For each key in prices, multiply the number in prices by the number in stock.
#Print that value into the console and then add it to total.
#Finally, outside your loop, print total.
prices = {"banana": 4,"apple": 2,"orange... |
1db6a10be20167e242bb50d4e5bdd26fe62d8631 | ayushi-b/HelloHadoop | /Example6/reducer.py | 791 | 3.5625 | 4 | #!/usr/local/bin/python3
import sys
last_page = None
max_visits = 0
most_visited_page = None
running_total = 0
for input_line in sys.stdin:
input_line = input_line.strip()
data = input_line.split("\t")
if len(data) != 2:
continue
this_page, value = data
value = int(value)
if la... |
4817cc6fd5f90f9af0e94a0db45efdad842e6751 | cold-rivers-snow/python | /identity.py | 705 | 4 | 4 | #!/usr/bin/python3
#id() 函数用于获取对象内存地址。
'''
is 与 == 区别:
is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。
'''
a = 20
b = 20
if(a is b):
print("1 - a和b有相同的标识")
else:
print("1 - a和b没有相同的标识")
if(id(a) == id(b)):
print("2 - a和b有相同的标识")
else:
print("2 - a和b没有相同的标识")
#修改变量b的值
b = 30
if(a is... |
9fc3a5ec7fde8ea9c0398af079d60e11db72f1de | jpcp13/L2 | /2017/Comptes-Rendus/TP1/Laiche_Belloucif/tp.py | 3,642 | 3.71875 | 4 | #(a) definition de f
def f(x):
return x**2 - x - 1
def df(x):
return 2*x -1
def g(x):
return 1 + 1/x
"""
def point_fixe(g, x0, epsi):
r= x0
#stock = []
i=1
nbiter = 0
while i == 1:
nbiter += 1
#stock.append(r)
prec = r
= g(r)
print(cpt)
if abs(r - prec) < epsi:
i = 0
return... |
bd31b457674273ca06c3d6605a613281e08797ff | viniciusdepadua/CES-22 | /lab1/Lab1.py | 4,963 | 3.765625 | 4 | import turtle
import math
import sys
import time
def test(did_pass):
linenum = sys._getframe(1).f_lineno
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = "Test at line {0} FAILED.".format(linenum)
print(msg)
def draw_this():
"""Makes a turtle draw 5 squares i... |
3c36d60657437173582b8909695cb995a74aafa3 | DanilKlukanov/Dynamic-programming-languages | /PyGame/E.py | 2,554 | 3.53125 | 4 | import pygame as pyg
import math
# инициализация
pyg.init()
# размеры окна
w, h = 1000, 1000
size = (w, h)
rad = 200
# scr — холст, на котором мы делаем отрисовку
scr = pyg.display.set_mode(size)
# отрисовка круга
points_multi = []
for i in range(1,361):
x = int(math.cos(math.radians(i)) * rad... |
959a1078f08b13b6aa8960d8995b4d718cf96af0 | JuliusMcW/GitCalc | /example.py | 187 | 3.6875 | 4 | def addition(op1, op2):
return op1+op2
def subtraction(op1, op2):
return op1-op2
def multiplication(op1, op2):
return op1*op2
def division(op1, op2):
return op1/op2
|
5e1e19447f232bb60b6c660ab016315856825d53 | dogukankotan/python | /gun_6/sayidan_yaziya.py | 668 | 3.84375 | 4 | def yazdir(say):
birler = ["", "bir", "iki", "uc", "dort", "bes"]
onlar = ["", "on", "yirmi", "otuz", "kırk", "elli"]
yuzler = "yuz"
basamak = len(say)
if basamak == 1:
if say == 0:
print("sıfır")
else:
print(birler[say])
elif basamak == 2:
print(o... |
26bf2f5f04ff98b120655e4e2fe64fea6edf11fb | mayank8200/Basic-Python-Programs | /Find Min and max using List.py | 310 | 4.1875 | 4 | #Write a program to get the max and min values from a dictionary
a={}
b=int(input("Enter the number of items:"))
for i in range(b):
k=int(input("Enter the key:"))
v=input("Enter the value:")
a[k]=v
l=[]
for i in a.values():
l.append(i)
print("The max is",max(l))
print("The min is",min(l))
|
f623b6fa67e35d52ecaa7da056ad4de450ad8a8e | dcchut/aoc2018 | /Day15/solution.py | 10,030 | 3.796875 | 4 | from collections import defaultdict
from utils import load_input
def simulation(board, attack_power):
b = defaultdict(bool)
units = {}
elves = []
goblins = []
k = 0
# go through every position on the board, marking whether it is a valid/invalid position for a unit to be
# we also determ... |
bce65facff9169389a19bfe5dfe3018279ad6d7e | sairatabassum/SQlite3_with_Python3 | /SQLite3 with Python 3.py | 1,876 | 3.9375 | 4 | import sqlite3
con = sqlite3.connect('student.db')
c = con.cursor()
#---Create Table---
def create_table():
c.execute("""CREATE TABLE IF NOT EXISTS students(
first text,
last text,
id integer
)""")
def data_entry():
c.execute("INSERT INTO ... |
f269faee6cb58f3903a397cfc653f0ab997be5cf | robsondrs/Exercicios_Python | /ex045.py | 722 | 3.65625 | 4 | from time import sleep
from random import randint
comp = randint(0, 2)
jokenpo = ['PEDRA', 'PAPEL', 'TESOURA']
print('''SUAS OPÇÕES:
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] TESOURA''')
jogador = int(input('Qual a sua jogada? '))
if -1 < jogador <=2:
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!')
... |
afdfbdd7a454a73e2477e4a2e61e396bb1fee806 | ottter/cryptopals | /set-1/0105-repeating-key-xor-encryptor.py | 462 | 3.65625 | 4 | input_text = b"Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
key = b"ICE"
def repeating_key_xor():
"""Set 1, Challenge 5
Encrypt the stanza, under the key "ICE", using repeating-key XOR"""
cipher = b''
i = 0
for byte in input_text:
cipher += bytes([byte ^ k... |
929271ad2a28207feb1b787648ee1be2ffcac5d1 | ProtulSikder/CodeChef | /ada and crayons.py | 419 | 3.5 | 4 | t = int(input())
for i in range(t):
n = input()
flag = 0
string = '0'
temp = n[0]
for i in n:
if i != temp:
temp = i
if flag%2 == 0:
string += '1'
else:
string += '0'
flag += 1
num_0 = string.count('0')
n... |
cc26f32cbd0c48cb4478914a66eba2f1d6392371 | Sharquo/_PythonProjs | /Programming Challenges/[2015-04-27] Challenge #212 [Easy] Rövarspråket.py | 446 | 4.09375 | 4 | def discombobulation():
normal_word = input("Please enter the word you want to Rövarspråket: ")
vowels = ["a", "e", "i", "o", "u", "y", "å", "ä", "ö"]
encoded_word = ""
for letter in normal_word.lower():
if letter.isalpha() and letter not in vowels:
encoded_word += letter + "o" + le... |
6ba4dab8cf3901ce15430d50c190bc5da0115948 | JakiShaik/Datastructures | /qselect.py | 659 | 3.734375 | 4 | from random import randint
def qselect(index, list):
if list == [] or index<1:
return None
else:
rand = randint(0,len(list)-1) #generates a random element from the list
pivot = list[rand] #rand index is set to pivot
#list.remove(rand)
left = [x for x in list if x< pivot]
... |
899a9cd58cad2df707b79e2cdf96df4ed645d67a | krzysieknaw/Algorithms_and_Data_Structures | /data_structures/stack_bin_to_dec.py | 727 | 3.71875 | 4 | from stack_implementation import Stack
def dec_to_bin(dec_num):
rs = Stack()
while dec_num>0:
r = dec_num%2
rs.push(r)
dec_num = dec_num//2
return_str = ""
while not rs.isEmpty():
return_str = return_str + str(rs.pop())
return return_st... |
d13ff83d81bf7c9fac64fe6adf87f2c23774c023 | novice1115/python_assignment | /46.py | 115 | 3.828125 | 4 | # finding length of the tuple
tuple1 = tuple("Insight")
print(tuple1)
print("Length of the tuple:\n", len(tuple1))
|
6470479a8687d03ae6a1b08201bfc20fbb5196c4 | heojungeun/codingtestPractice | /test.py | 246 | 3.71875 | 4 | # for else 문은 for 문이 break 없이 끝나면 수행하는 것.
def nsys(number, base):
notation = "0123456789ABCDEF"
q,r = divmod(number,base)
num = notation[r]
return nsys(q,base) + num if q else num
a = [1]
print(a[-1]) |
b8ae203e5bcfb9766e223e967eca770bcbd1044c | sandro-fidelis/Cursos | /Curso Python/ex058.py | 366 | 3.921875 | 4 | from random import randint
j = int()
cont = 0
c = randint(1,10)
print('Pensei em um número entre 0 e 10. ')
while c != j:
j= int(input('Qual é o seu palpite: '))
cont += 1
if c > j:
print('Dica: O número é maior. ')
elif c < j:
print('Dica: O número é menor. ')
else:
print('ACERTTOUUU!!!, Voçê ace... |
cac88a4ee5de05d92b1fb17948f5864e05e9e0e3 | skytreader/pydagogical | /algorithms/tests/binary_search_tests.py | 2,111 | 3.90625 | 4 | from ..binary_search import binary_search, binary_insert
import unittest
class FunctionsTest(unittest.TestCase):
def test_binary_search(self):
"""
Test cases:
even-length list positive result
even-length list negative result
odd-length list positive result
odd... |
75d743e8981a32a1886f7f1ffa82fdfb05d22a23 | apoorvmaheshwari/pythontrain | /DXCTraining/Examples/11SampleModules/tk/3Radio/first.py | 605 | 3.9375 | 4 | # !/usr/bin/python3
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text=selection)
root = Tk()
var = IntVar() # The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
... |
0e3e5b1cc341e9a370dffd8f56e5bc7016a7553d | jfrausto7/HelloWorldPython | /Matplotlib_bar.py | 374 | 3.578125 | 4 | # imports
import matplotlib.pyplot as plt
import numpy as np
# set size
fig = plt.figure(figsize=(7,5))
# data
names = ["Scott", "Jacob", "Michael", "Brennan"]
scores = [88, 57, 92, 34]
# set positions based on length of scores array
positions = np.arange(len(scores))
# actual bar chart
plt.bar(positions, scores)
pl... |
11756b5204a53f490479d21a692e939e79f53957 | Adroit-Abhik/CipherSchools_Assignment | /matrixSpiralTraversal.py | 810 | 3.96875 | 4 | def spiraltraversal(arr, row, column):
l = 0
m = 0
# l starting row indx
# row ending row idx
# m starting col idx
# column starting idx
while l < row and m < column:
# --->
for i in range(m, column):
print(arr[l][i], end=" ")
l += 1
# |
f... |
ffc87c21f571169d53153b386f68b6854a3c1cb1 | berkesenturk/Turtle-Race | /turtlerace.py | 1,516 | 4.0625 | 4 |
from random import randint
from turtle import *
screen = Screen()
screen.screensize(2000,1500)
screen.title("Turtle Race")
screen.bgcolor("yellow")
penup()
goto(0,220)
write("Hit SPACE!!",font=("Arial", 12, "bold"))
goto(-160,130)
for step in range(25):
speed(1000)
write(step, align='center')
right(90)... |
a2d578c887638d0e46f10b26cae4218937f09c73 | kongjun0320/PythonNote | /day01/homework.py | 1,251 | 4.03125 | 4 | # in 和 not in 的补充
# 判断字符或者字符串有没有在另一个字符串中出现 有则返回True 无则返回False
"""
my_str = '我爱我的祖国-中国'
print('中国' in my_str) # True
print('中国人' in my_str) # False
"""
# 练习:判断用户输入的内容是否包含铭感字符
"""
while True:
input_str = input("请输入:")
if input_str in '我是敏感字符':
continue
else:
print(f"请输入的内容是{input_str}")
... |
27750a3bc0fd92dbce994e4a5309de8f6823591e | jdanray/leetcode | /trailingZeroes.py | 161 | 3.515625 | 4 | # https://leetcode.com/problems/factorial-trailing-zeroes/
class Solution:
def trailingZeroes(self, n):
z = 0
while n > 0:
n //= 5
z += n
return z
|
a4b6465c41ce20778a467e45fd09b5a1cfef0b78 | samuelpereira7/Python-on-Galileo-Edison | /part1-blinky/blink.py | 1,082 | 3.9375 | 4 | #!/usr/bin/python
import mraa # For accessing the GPIO
import time # For sleeping between blinks
"""
This script demonstrates the usage of mraa library for controlling a
GPIO as output
setup:
The LED is connected port D5
Demo:
start the application in the command line by using following command:
python bl... |
3d8b87ea4547e1cf08a6990cf3f39cab266f97c1 | howletmj/ECE434 | /hw01/etch_matt_howlett.py | 2,029 | 3.96875 | 4 | #!/usr/bin/env python3
def main():
etchwinsize=int(input("Window Size nxn n = "))+1 #window size plus one column for row numbers
cursorlocation = etchwinsize+2 #sets default location of cursor
display_array = ["1"]*etchwinsize*etchwinsize #initial display array
while(1):
display_array = renderdisplay(curso... |
f03906d4ec85d2bf618172c7d3f9c80a75280465 | xpgeng/leetcode | /Python/Hamming_Distance.py | 1,033 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
he Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑... |
931e8674930bbe5f961053eb3e91168bc4952a33 | TarunKalva/Advanced_Python_Django_LetsUpgrade | /Day-13 Assignments APD-LU.py | 982 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Assignment 1
# Remove the hardcoded part from the code with the help of configparser. use file exc.in
# In[1]:
from configparser import ConfigParser as cp
# In[2]:
config=cp()
config.read('exc.ini')
print(config.sections())
print(config.options('FC'))
# In[3]:
impor... |
5c74a4a10ffc053b2b7221ff86b5147aa72aac36 | rafamonge/Practica | /Chapter3/MinStack.py | 1,587 | 3.890625 | 4 | # %%
class Node:
def __init__(self, value, next):
self.Value = value
self.Next = next
class Stack:
def __init__(self):
self.Head = None
def is_empty(self):
return self.Head == None
def push(self, value):
self.Head = Node(value, self.Head)
def pop(self):... |
cc56dfdff27eb39b30e51a845a821f76bb1c1f5f | JakubKazimierski/PythonPortfolio | /AlgoExpert_algorithms/Medium/ThreeNumberSort/test_ThreeNumberSort.py | 940 | 3.671875 | 4 | '''
Unittests for ThreeNumberSort.py
February 2021 Jakub Kazimierski
'''
import unittest
from ThreeNumberSort import threeNumberSort
class test_ThreeNumberSort(unittest.TestCase):
'''
Class with unittests for ThreeNumberSort.py
'''
def SetUp(self):
'''
Set Up input ... |
9a983250fa139bde0b69bde785d62391d27cb20f | vedant-kulk/Second-Year-SPPU-Assignments | /Fundamental Of Data Structure(FDS)/Assignment_1 (Set Operations).py | 4,604 | 4.125 | 4 | """
Problem Statement::
In second year computer engineering class, group A student’s play cricket, group B students play badminton and group C students play football.
Write a Python program using functions to compute following: -
a) List of students who play both cricket and badminton
... |
9a75b5b8309649e5f0aa8f7d064b6a92d62ab173 | Omkarr93/first_repo | /03_remiander.py | 67 | 3.734375 | 4 | a= 47
b = 5
print("The remainder when a is divded by b is: ",a%b) |
85d632a7a995c1629f1b616ccf9f6fb7cd1f0c9f | vish4luffy/Codewars_kata | /kataTrain3.py | 885 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 1 23:47:32 2018
@author: Gireesh
"""
# At the end of the first year there will be:
# 1000 + 1000 * 0.02 + 50 => 1070 inhabitants
# At the end of the 2nd year there will be:
# 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)... |
7d19504775fd2d5aee3c865382619c35e61c1bcf | Yogayu/ComputerScience-KnowledgeSystem | /Algorithm/CTCI/LinkedList.py | 1,631 | 4.125 | 4 | '''
@author: youxinyu
@date: 2018-8-29
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
if self.head == None:
self.head = Node(data)
else:
... |
7fd584a2d4988005f93191169f6709b9d68709cb | palakala/Python-Programming | /LinkedList/LinkedListInsert.py | 2,182 | 4.125 | 4 | class Node:
def __init__(self,info,link=None):
self.info=info
self.link=link
class LinkedList:
def __init__(self):
self.head=None
def insertAtBegin(self,info):
newNode = Node(info)
if self.head== None :
self.head= newNode
else:
... |
47833ce6d11fb6b863f8aa2f24e53667289bbab0 | me-smishra27/100-days-of-Python-Code-Challenge | /Factorial.py | 720 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#Find the factorial of number
#Using Built in Function
num = int(input("Enter the Number to find factorial: "))
import math
fact = math.factorial(num)
print(fact)
#Using Recursion Method
def fact(num):
if num == 0:... |
7f6f9a9db8bd8acb195ff194abf0c3a8daa47c5f | yuriyshapovalov/Prototypes | /ProjectEuler/python/prob19.py | 1,261 | 3.765625 | 4 | # projecteuler.net/problem=19
days = ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
month = ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')
d_mon = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
d_mon_leap = ( 31, 29, 31, 30, ... |
4c6011efe2f49d60162e4119917c518c0977b010 | JuanGinesRamisV/python | /practica 6/p6e9.py | 604 | 3.828125 | 4 | #juan gines ramis vivancos p6ej9
#Escribe un programa que te pida nombres de personas y sus números de teléfono. Para terminar debe pulsar “S”
usuario=[]
usuarios=[]
print('introduce tu nombre de usuario')
nombre=str(input())
print('introduce tu numero de telefono')
telefono=int(input())
while nombre !='s':
usuario... |
3bb30ba4499872a54786b4963bff6e0028924356 | Aya-Mahmoud-99/MinMax | /numberscrabble.py | 1,648 | 3.546875 | 4 | ##3 empty
import copy
class Game:
def get_actions(self,state):
return state[3]
def is_terminal(self,state):
if len(state[3])==0:
return True, "draw"
p1_tiles=state[1]
p2_tiles=state[2]
sums=[]
#N*(N2+ 1)/2.
target=state[0]*(state[0]... |
0377b7693ba3d6947188961eb6ca8afc20735ee6 | Wanger-SJTU/leetcode-solutions | /python/10.RegularExpressionMatching.py | 1,554 | 3.671875 | 4 |
'''
递归:
'''
# 没有 * 的递归解法
# 从左往右匹配
def match(text, pattern):
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
return first_match and match(text[1:], pattern[1:])
# 有 * 的递归解法
# 如果下一个是 * 匹配的结果是 当前匹配的结果-
# first_match && src[1:] 与pattern(匹配*) && src 与 pattern... |
6052189dada5e345a35a6c5706792863bdb4ea86 | TonyCioara/CS1 | /Gradebook_Project/student.py | 2,905 | 4.0625 | 4 | class Student:
'''Class of student objects that will populate each class roster.
Each student object contains the following attributes:
_____Attributes_______
_student_ID: Int. A unique integer identifier assigned to each student at the object's creation.
name: String. The name of the student.... |
01e2342c2491c03cd35c670c12f74e7573e3071b | chunisama/leetcode | /EoP - Python/W2D5/coins_for_max_gain.py | 590 | 3.6875 | 4 | # Design an efficient algorithm for computing the maximum total value for
# the starting player in the pick-up-coins game.
# redo
# coins = [25, 5, 10, 5, 10, 5, 10, 25, 1, 25, 1,25 ,1 ,25, 5, 10]
# coins = [5, 25, 10, 1]
def coin_change(coins, amount):
ways = [float("inf") for i in range(amount + 1)]
ways[0] = ... |
7104bf4589c8e408f39d63a5562cffb9b7ae4a10 | jasonchadwick/quantum-checkers | /quantum_checkers_hexagonal.py | 9,067 | 4.125 | 4 | import numpy as np
from numpy.lib.function_base import _calculate_shapes
from gates import *
from game_utils.hex_board import HexBoard
"""
All tiles are entangled - i.e. the entire board is in a superposition of possible
states. These states have different "probability amplitudes" associated with them.
As in quantum ... |
6acad7b71e0367482250c4952f27cd86a2cb638e | bo0tzz/AdventOfCode | /2018/02/day2_1.py | 544 | 3.84375 | 4 | def contains_count(word: str, expected_count: int):
letters = {}
for letter in word:
letters[letter] = letters.setdefault(letter, 0) + 1
return {letter: count for letter, count in letters.items() if count is expected_count}
with open('in.txt') as puzzle_input:
two_uniques, three_uniques = 0, 0... |
6334b25263f2f84caf76b6b77c8a7f33f7719ae5 | RazLandau/pybryt | /max_even_seq/subs/2017B/27.py | 283 | 3.609375 | 4 | def max_even_seq(n):
max_seq = 0
counter = 0
for i in str(n):
i = int(i)
if i % 2 == 0:
counter += 1
else:
max_seq = max(counter, max_seq)
counter = 0
max_seq = max(counter, max_seq)
return max_seq
|
d360999f111ef3dcbbe87d512881d59189e50857 | Gustavokmp/URI | /1161.py | 611 | 3.703125 | 4 | while True:
try:
numero = input()
numero = numero.split()
n1 = int(numero[0])
n2 = int(numero[1])
soma_total = 0
soma_n1 = 0
soma_n2 = 0
if(n1 == 0):
soma_total += 1
if(n2 == 0):
soma_total += 1
if(n1 != 0):
... |
a66061ec7a12dbd640ec9a965213f5c26367131f | GoodestUsername/Python-examples-from-school | /Lab/Lab6/auction_simulator.py | 6,590 | 3.828125 | 4 | """
Implements the observer pattern and simulates a simple auction.
"""
import random
def get_valid_user_input_for_specified_type(msg, type_converter_function):
"""
Asks user to enter input until the user enters an input that can be converted using the type_converter_function.
:param msg: A string message... |
6bbf0b2f73bb8571f3b7f4e662dbfc384677ab55 | mashabulkahfi/Seleksi-1-Asisten-LabPro-2018 | /2-Problem11.py | 466 | 3.59375 | 4 | message = input("Masukan teks terenkripsi: ")
n=input("Masukan nilai N :")
N=int(n);
dmessage = ""
for ch in message:
char = ord(ch)
if ((char>=ord('a')) and (char<=ord('z'))):
if (char-N < ord('a')):
char=char+ord('z')-N-ord('a')+1
else :
char=char-N
dmessage = dmessage + str(char) +" "
deco... |
f2afafad16a74bcf731715454636234b44b562d1 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2382/60622/317068.py | 146 | 3.6875 | 4 | n=int(input())
l=[]
for i in range(n):
s=input()
l.append(s)
print(l)
# print("1 4")
# print("5 10")
# print("12 13")
# print("16 18") |
c075a09774ba1f42a41be33c30716e4b7f848dbc | Sumanth-Sam-ig/pythoncode | /even or odd .py | 153 | 4.09375 | 4 | print('enter the number')
a=int(input())
if a<0 :
print('invalid entry')
if a%2==0 :
print('number is even')
else :
print ('number is odd') |
a4ff4ffe5cd884b49c354f10b318358e262aaa2d | wjosew1984/ejerciciospython1 | /buclewhile.py | 559 | 4.0625 | 4 | #Escribe las líneas que faltan en el código para que se escriba del 1 al 12.
a = 0
while a < 12:
a = a + 1
print ( a )
#2. Modifica el código anterior para que se cree un contador infinito.
#3. Escribe la línea de código que falta de forma que el programa pregunte por el nombre, hasta que se escriba Carlo... |
2978f1ca76674fd9da9482ef1b3a72d79b4423b6 | djaychela/100daysofpythoncode | /day16_18/day17_01.py | 636 | 3.640625 | 4 | import random
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
def pairs_gen():
for i in range(10):
... |
bf52e876f8a97cdd3d39fb1a619f7dabd6ba82ce | gokou00/python_programming_challenges | /coderbyte/SquareFigures.py | 297 | 4.03125 | 4 | def SquareFigures(num):
squrt = 1
squrtStr = ""
count = 1
if num == 1:
return 0
while len(squrtStr) < num:
squrt = count ** 2
squrtStr = str(squrt)
count += 1
#print(squrt)
return count -1
print(SquareFigures(3)) |
a28f478949c9b9d08733f7e16e1894a0c6165e9d | seokhyeon99/ML | /source_code_ch04/4. Regression.py | 4,388 | 3.5 | 4 | '''
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
Boston = pd.read_csv('d:/data/dataset_0914/BostonHousing.csv')
#print(Boston)
lst... |
b9e557ee5f69f951c65761ff1aff6fe64d39fb5b | nikonst/Python | /someTopics/copies.py | 753 | 3.859375 | 4 | print("EQUALS")
l1 = [1,2,3,4,5]
l2 = l1
print("l1 = ",l1)
print("l2 = ",l2)
print("l1:",id(l1))
print("l2:",id(l2))
l1.append(6)
print("l1 = ",l1)
print("l2 = ",l2)
print("l1:",id(l1))
print("l2:",id(l2))
import copy
#Shallow Copy
print("\nSHALLOW COPY")
l3 = copy.copy(l1)
print("l1 =",l1)
print("... |
0ea67fc7cec22cbb6fb2497b33901db66b215c38 | vipuldhandre/PHP | /set_examples.py | 1,670 | 4.25 | 4 | #Set :
#empty set
#s = set()
#type(s1)
# Unordered,mutable,heterogeneous,insertion order is not preserved.
#WAP to print 25 elements in a set.
"""
x = [x for x in range(25)]
s = set(x)
print(s)
"""
# set doesn't mutable data.
# s = {1,2,[4,5,6],7,8}
# error: Unhashable type s
"""
s = set()
s.add(2)
s.add("vipul")
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.